Hari Om Gaur
abouttalksuvacha

Ruby Hashes

May 28, 2015

A collection of unique keys and their value

Tweet Follow @hogaur


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={}
A Hash can also be created using the method Hash#new-
hash_map=Hash.new
A hash key-value pair can have any object as its key. e.g. price and volume below, use objects of class String and Symbol respectively and both are valid hashes-
price = {"pepsi"=>10, "cola"=>10, "amul"=>20}
volume = {:pepsi=>330, :cola=>330, :amul=>200}
In fact, a hash can have different object types as its keys. e.g. a_hash below is a valid hash too-
a_hash = {:a_symbol => "symbol it is", "a_string" => "string it is"}
In case you want to access a key that has not been added to a hash, a default value is returned. If default is not set, nil is returned. You can set the default value by passing it as an argument to new or calling the Hash#default method -
price = Hash.new(0)
price.default = 0 
Fetching values from a Hash and modifying it- you can fetch values from a Hash by putting the key name in square bracket after the Hash name. And just in case you want to modify them, writing the new value in front of the above is enough.
price[:pepsi] #=>fetches value corresponding to key :pepsi i.e. 10
price[:pepsi] = 20 #=> assigns the value 20 to the key :pepsi
If you want to list down all the keys in a Hash, price.keys will get you an array of all the keys in hash price.

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
Hash#map iterates over a Hash and returns an array with result of running block for each element of Hash.
price = {"pepsi" => 10, "cola" => 10, "amul" => 20}
price.map {|key, value| [key.to_sym , value.to_s ] }
#=> [[:pepsi,"10"], [:cola, "10"], [:amul, "20"]]

Hari Om Gaur

  • hogaur
  • hogaur@gmail.com
  • hogaur
  • hogaur
  • hogaur

My journey, learnings & experiences about software engineering, life & music.