Ruby Hashes
A collection of unique keys and their value
Hashes also called Associative arrays, are similar to arrays in the way
that arrays use integers as their keys (array indexes). A hash allows
you to use any objects as keys.
Declaring a blank hash is as simple as writing -
hash_map={}
hash_map=Hash.new
price = {"pepsi"=>10, "cola"=>10, "amul"=>20}
volume = {:pepsi=>330, :cola=>330, :amul=>200}
a_hash = {:a_symbol => "symbol it is", "a_string" => "string it is"}
price = Hash.new(0)
price.default = 0
price[:pepsi] #=>fetches value corresponding to key :pepsi i.e. 10
price[:pepsi] = 20 #=> assigns the value 20 to the key :pepsi
Hash#each, map
You can iterate over a Hash using Hash#each method. It is similar to
Array#each method but passes two values to the block parameters, the
key and the value of each element.
price.each do |key, value|
puts "Price of #{key} is #{value}"
end
price = {"pepsi" => 10, "cola" => 10, "amul" => 20}
price.map {|key, value| [key.to_sym , value.to_s ] }
#=> [[:pepsi,"10"], [:cola, "10"], [:amul, "20"]]