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

#!/usr/bin/ruby
# 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

#!/usr/bin/ruby
# File: rubyhashforeach.rb
 
address.each do |key, value| 
	puts key + " - " + value 
end

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.