ruby hash

A Hash stores information in the form of a key value pair. KEY VALUE yunnan kunming
sichuan chengdu guizhou guiyang

In the hash given above, the key is the country name and the value is the city of the province.

hash = {
 "yunnan" => "kunming ",
 "sichuan" => "chengdu",
 "guizhou" => "guiyang",
}
puts hash
puts hash["yunnan"]

// Add Data to a Hash Using Key
hash.merge!({"guangdong" => "guangzhou"})
puts hash

hash["nanning"] = "guangxi"

Hash provides the method keys to list all keys from a hash.

hash = {
 "yunnan" => "kunming ",
 "sichuan" => "chengdu",
 "guizhou" => "guiyang",
}
all_keys = hash.keys

puts all_keys

Just like Array and Range, Hash also supports each do.

hash = {
 "yunnan" => "kunming ",
 "sichuan" => "chengdu",
 "guizhou" => "guiyang",
}

hash.each do |key, value|
   puts "city of #{key} is #{value}"
end