Skip to content
the poor coder

Hackerrank Ruby Hash - Each Solution

Poor Man
Published
Updated
Reading time
1 min read

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

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

Using each, each element can be iterated as

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

or

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

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

Hint

Text
puts key
puts value

Solution in ruby#

Approach 1.

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

Approach 2.

Python
def iter_hash(hash)
    hash.each do |key,value|
        puts key
        puts value
    end
end

Approach 3.

Python
def iter_hash(hash)
    hash.each do |key, value|
        puts key
        puts value
    end
end

Keep going

ESC