Tutorial on creating and using hash in Ruby and ruby hash
Hash is a set of key-value pairs similar to "employee" => "salary. Hash indexes are completed by any key of any object type, rather than an integer index. Others are similar to arrays.
The hash traversal order by key or value seems random, and is generally not in the insertion order. If you try to access the hash using a key that does not exist, the method returns nil.
Create a hash
Like arrays, there are different ways to create a hash. You can create an empty hash using the new class method:
months = Hash.new
You can also use new to create a hash with the default value. The hash without the default value is nil:
months = Hash.new( "month" ) or months = Hash.new "month"
When you access any key in the hash with the default value, if the key or value does not exist, the default value is returned for accessing the hash:
#!/usr/bin/ruby months = Hash.new( "month" ) puts "#{months[0]}"puts "#{months[72]}"
This produces the following results:
monthmonth#!/usr/bin/ruby H = Hash["a" => 100, "b" => 200] puts "#{H['a']}"puts "#{H['b']}"
This produces the following results:
100200
You can use any Ruby object as a key or value or even an array. Therefore, the following example is a valid example:
[1,"jan"] => "January"
Hash built-in method
We need an instance of the Hash object to call the Hash method. The following describes 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 filled with the given object. Now, using the created object, we can call any available instance method. For example:
#!/usr/bin/ruby $, = ", "months = Hash.new( "month" ) months = {"1" => "January", "2" => "February"} keys = months.keys puts "#{keys}"
This produces the following results:
2, 1
The following is a public hash method (assuming that Hash is a hash object ):