A hash is an data structure which stores items by asociated keys which is differentiated against arrays and which store items by an indexed order. Entries in a hash are regularly alluded to as
key-values pairs which makes a associative representation of data. Most normally, a hash is made utilizing symbols as keys and any data types as values. All key-value pairs in a hash are encompassed by
curly braces {} and <span style="color: #ff6600;"comma seperated.
Hashes can be made with two syntax's in which old syntax comes with
=> sign to isolate the key and the value. The code below demonstrates the older syntax of Hash as shown below.
[ruby]
old_syntax_hash = {:name => 'bob'}
=> {:name=>'bob'}
[/ruby]
In Ruby 1.9 a new syntax introduced which is simpler then older syntax but it produce the same result. The code below demonstrates the Hash new syntax as shown below.
[ruby]
new_hash = {name: 'bob'}
=> {:name=>'bob'}
[/ruby]
The code below demonstrates to creating the hashes as shown below.
[ruby]
months = Hash.new( "month" )
puts "#{months[0]}"
puts "#{months[72]}"
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.
If Ruby have multiple elements when user want to iterate over a hash with each element which is similar to iterating over arrays with some differences in which user need to use the each method. The code below demonstrates to iterating over hashes as shown below.
[ruby]
person = {name: 'bob', height: '6 ft', weight: '160 lbs', hair: 'brown'}
person.each do |key, value|
puts "Bob's #{key} is #{value}"
end
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.