[BlogEntry] Iterating over a Hash in Ruby

0

Let's say you define a simple Hash.

irb(main):001:0> h1 = {"a"=>1,"b"=>2,"c"=>3}
=> {"a"=>1, "b"=>2, "c"=>3}

What do you think you'll get when you send an each message to it? I figured either a, b, c or 1, 2, 3. Surprise:

irb(main):003:0> h1.each{|a| puts a}
a
1
b
2
c
3
=> {"a"=>1, "b"=>2, "c"=>3}

It all comes out, keys and values interleaved.

Now, the trick becomes figuring out what to Google for to learn the syntax that gets you just the part of the hash you're after. Let me save you a little time. What you're after is each_value.

irb(main):008:0> h1.each_value {|a| puts a}
1
2
3
=> {"a"=>1, "b"=>2, "c"=>3}

You can also use each_key. Fairly intuitive, once you know it. Ah, there's the rub. 🙂

irb(main):009:0> h1.each_key {|a| puts a}
a
b
c
=> {"a"=>1, "b"=>2, "c"=>3}

Leave a Reply

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

CommentLuv badge