Question

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!

Was it helpful?

Solution

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]}" }

OTHER TIPS

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"]

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top