The basic usage of hash in Ruby, and the usage of Rubyhash
A set of hash key-value pairs, such as "employee" => "salary ". It is similar to an array, except that the index is any object type through any key, rather than an integer index.
Traversing a hash key or value in sequence may either look arbitrary and will not insert the value in the sequence. If the hash value of the accessed key does not exist, this method returns nil.
Create a hash:
There are various methods in the array to create hash values. You can create an empty hash using the new class method:
months = Hash.new
You can also use new to create a hash. This is a default value, otherwise it is only nil:
Copy codeThe Code is as follows: months = Hash. new ("month ")
Or
Months = Hash. new "month"
When accessing any hash key, there is a default value. If the key or value does not exist, the default value will be returned for accessing the hash table:
#!/usr/bin/rubymonths = Hash.new( "month" )puts "#{months[0]}"puts "#{months[72]}"
This produces the following results:
monthmonth#!/usr/bin/rubyH = Hash["a" => 100, "b" => 200]puts "#{H['a']}"puts "#{H['b']}"
This produces the following results:
100200
If any Ruby object can be used as a key, value, or even an array, the following example is valid.
[1,"jan"] => "January"
Built-in hashing methods:
We need a Hash object instance to call the Hash method. As we can see, the following is a Hash object method to create an instance:
Hash[[key =>|, value]* ] orHash.new [or] Hash.new(obj) [or]Hash.new { |hash, key| block }
This will return a new hash value with a given object fill. 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.keysputs "#{keys}"
This produces the following results:
2, 1