-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!

4

3 回答 3

3

each_value您可以使用;遍历哈希的所有值 或者,您可以使用 遍历哈希的所有键/值对each,这将产生两个变量,键和值。

如果你想为外部散列的每个散列值打印一个值,你应该这样做:

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

这是一个更复杂的示例,展示了其each工作原理:

ary.each { |key, value| puts "the value for :label for #{key} is #{value[:label]}" }
于 2013-04-30T07:58:15.750 回答
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"]
于 2013-04-30T08:11:05.300 回答
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.values.each {|v| puts v[:label]}
  label_1
  label_2
  label_3
于 2013-04-30T08:37:03.330 回答