Skip to main content

Ruby Hash

Ruby Hash

Hash is a collection of key-value pairs like "key" => "value". A hash is similar to an array, except that its indexing is not limited to using numbers.

The index (or "key") of a Hash can be almost any object.

Although Hash is similar to array, it has an important difference: the elements of Hash have no specific order. If order is important then use an array.

Create a hash

As with arrays, there are various ways to create hashes. You can create an empty hash via the new class method:

 
months = Hash.new

You can also use new to create a hash with a default value, a hash without a default value is nil :

  months = Hash.new( "month" )



or



months = Hash.new "month"



When you access any key in a hash with a default value, accessing the hash will return the default value if the key or value does not exist:

Example

  months = Hash.new( "month" )



or



months = Hash.new "month"



The output result of the above example is:

  month

month



Example

  #!/usr/bin/[[ruby](/search?q=ruby)](/search?q=ruby)



H = Hash["a" => 100, "b" => 200]



puts "#{H['a']}"

puts "#{H['b']}"



The output result of the above example is:

  100

200



You can use any Ruby object as a key or value, even an array, as shown in the following example:

 
[1,"jan"] => "January"

Hash built-in methods

If you need to call the Hash method, you need to instantiate a Hash object first. Here's how to create a Hash object instance:

  Hash[[key =>|, value]* ] or



Hash.new [or] Hash.new(obj) [or]



Hash.new { |hash, key| block }



This will return a new hash populated with the given object. Now, using the created object, we can call any of the available methods. For example: