Ruby - Hash Hash Creation

Introduction

Ruby hash is a dictionary or associative array.

Each entry is indexed by a unique key that is associated with a value.

Creating Hashes

You can create a hash by creating a new instance of the Hash class:

h1 = Hash.new 
h2 = Hash.new("Some value") 

Both the previous examples create an empty Hash object.

A Hash object always has a default value.

The default value is a value that is returned when no specific value is found at a given index.

In the above examples, h2 is initialized with the default value "Some value"; h1 is not initialized with a value, so its default value will be nil.

For a Hash object, you can add items to it using an arraylike syntax.

With an array, the index (or key) must be an integer; with a hash, it can be any unique data item:

h2['Product1'] = 'A' 
h2['Product2'] = 'B' 
h2['Product3'] = 'C' 
h2['Product4'] = 'D' 

The key may be a number or a string.

In principle, a key can be any type of object.

Related Topics