Ruby Hash

Ruby hashes are equivalent to Java Hashmaps and allows us to store information as key-value pair in contrast to arrays in which we can have only integer keys or indices. Thus, Ruby hashes are generalization of arrays.

Ruby Hash Example

# File: rubyhash.rb

address = {
“First name” => “Anthony”,
“Last name” => “Moody”,
“Street” => “101 LA Street”,
“City” => “CA”,
“Country” => “US”

puts address[‘City’]

Output of the above code would be CA.

Ruby Hashes Iteration through Foreach

# File: rubyhashforeach.rb

address.each do |key, value|
puts key + ” – ” + value

This would output:

“First name” – “Anthony”,
“Last name” – “Moody”,
“Street” – “101 LA Street”,
“City” – “CA”,
“Country” – “US”

Having learnt Ruby arrays and hash, now learn how to convert Ruby arrays to hashes.