ruby hash

wang xiao bo 's photo
wang xiao bo

Published on Sep 2, 2021

1 min read

Subscribe to my newsletter and never miss my upcoming articles

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
 
Share this