Hackerrank Ruby Hash - Each Solution
1 min read

Hackerrank Ruby Hash - Each Solution

Hackerrank Ruby Hash - Each Solution

.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

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×