Iterating over a Hash in Ruby
There are two iterators that allows you to iterate over hashes. They are both methods of a Hash class and allow you to extract key-value pair from your hash: each_pair and each. The only difference between these two methods is that each_pair returns key-value pair in a random order as well as more it is more efficient if compared to each.
my_hash = {‘one’ =>1, ‘two’=>2}
my_hash.each_pair {|key, value| puts “#{key} - #{value}”}
In addition to each_pair and each, there are other iterators available to you as a part of standard Hash implementation.
my_hash.each_key{|key| puts key}
my_hash.each_value{|value| puts value}
However, you should never use each_value if your object is to find one single value in the hash. You should employ has_value? method instead
my_hash.has_value? 1
You can always iterate through a hash by converting it to an array first with the help of to_a method.
my_hash.to_a
Hashes are known for returning key-value pair in random order, so in order to return a particular order form a hash, you should convert it to an array, sort array and then return a key-value pair in your desired order.
Hash class has two methods, namely sort and sort_by, that help you to convert your hash into an array of two element subarrays.
my_hash.sort_by{|id, number| [number,id]}.each{|key,value|puts key}
You can also apply hash inversion by switching keys and values with the help of invert method.
One final way of getting a key-value pair out of hash is to employ grep which allows you to get key-value pair with the help of regular expression.
my_hash.keys.grep /1/
Alternatively, you can iterate over hash and employ regular expression which may be faster if your memory is limited.
my_hash.each_key {|k| new_hash<<key if key=~/1/}