You've successfully subscribed to The Poor Coder | Hackerrank Solutions
Great! Next, complete checkout for full access to The Poor Coder | Hackerrank Solutions
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Hackerrank Ruby Hash - Each Solution

Hackerrank Ruby Hash - Each Solution

Beeze Aal
Beeze Aal

.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}

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
end

or

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

puts key
puts value

Solution in ruby

Approach 1.

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

Approach 2.

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

Approach 3.

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