Ruby Hash – Each Solution

In this post, we will solve Ruby Hash – Each HackerRank Solution. This problem (Ruby Hash – Each) is a part of HackerRank Ruby series.


You’ve seen the control structure each used on an array. Similarly, it is available for the Hash collection, as well.

On Hash, it works in two ways.

Consider the example

user = {"viv" : 10, "simmy" : 20, "sp2hari" : 30}

Using each, each element can be iterated as

user.each do |key, value|
    # some code on individual key, value


user.each do |arr|
    # here arr[0] is the key and arr[1] is the value

Your task is to use each and iterate through the collection and print the key-value pair in separate lines.


puts key
puts value

Solution – Ruby Hash – Each

def iter_hash(hash)
    hash.each do |k, v|
        puts k
        puts v

Note: This problem (Ruby Hash – Each) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *