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/}

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…