-1

I am a beginner and am looking for a method to iterate through a hash containing hashed values. E.g. I only want to print a list of all values of inner hash-elements of the key named "label". My array is looking like this:

ary = Hash.new
ary[:item_1] = Hash[ :label => "label_1" ]
ary[:item_2] = Hash[ :label => "label_2" ]
ary[:item_3] = Hash[ :label => "label_3" ]

Now I want to iterate through all elements of the outer hash and try this:

ary.keys.each { |item| puts ary[:item] }

or this:

ary.keys.each { |item[:label]| puts ary[:item] }

Unfortunately both do not work. But if I try this - quite crazy feeling - detour, I get the result, which is I want to:

ary.keys.each { |item|
    evalstr = "ary[:" + item.to_s + "][:label]"
    puts eval(evalstr)
}

This yields the result:

label_1
label_2
label_3

I am absolutely sure that there must exist be a better method, but I have no idea how to find this method.

Thanks very much for your hints!

  • ary.keys.each { |item| puts ary[item][:label] } would have worked. But the ary.each_values answer below is a cleaner solution. – James Apr 30 '13 at 08:05

3 Answers3

3

You can iterate through all values of an hash using each_value; or, you can iterate trough all key/value pairs of an hash using each, which will yield two variables, key and value.

If you want to print a single value for each hash value of the outer hash, you should go for something like this:

ary.each_value { |x| puts x[:label] }

Here's a more complex example that shows how each works:

ary.each { |key, value| puts "the value for :label for #{key} is #{value[:label]}" }
giorgian
  • 3,795
  • 1
  • 30
  • 48
0
ary = Hash.new
ary[:item_1] = Hash[ :label => "label_1" ]
ary[:item_2] = Hash[ :label => "label_2" ]
ary[:item_3] = Hash[ :label => "label_3" ]
ary.flat_map{|_,v| v.values}
#=>["label_1", "label_2", "label_3"]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0

See Hash methods

> ary = Hash.new
> ary[:item_1] = Hash[ :label => "label_1" ]
> ary[:item_2] = Hash[ :label => "label_2" ]
> ary[:item_3] = Hash[ :label => "label_3" ]

> ary.values.each {|v| puts v[:label]}
  label_1
  label_2
  label_3
shweta
  • 8,019
  • 1
  • 40
  • 43