Ruby:在哈希中选择数组中的值

时间:2017-01-24 16:50:42

标签: arrays ruby hash

我想迭代哈希每个数组的每个值。通常,要选择数组中的值,我会这样做:

array = ["1", "2"]
array.each do |x| puts x end

但如果它在散列中,我如何遍历数组呢?

这是我的代码:

hash = {1 => {"a1" => ["un", "uno"], "a2" => ["uunn", "uunnoo"]}, 2 => {"b1" => ["deux", "dos"], "b2" => ["ddeuxx", "ddooss"]}}

hash.each do |key, key2, value|
    puts key
    hash[key].each do |key, value|
        puts key
        #insert here the code to iterate through the array
    end
end

这是我找到的最符合逻辑的东西但不起作用:

hash = {1 => {"a1" => ["un", "uno"], "a2" => ["uunn", "uunnoo"]}, 2 => {"b1" => ["deux", "dos"], "b2" => ["ddeuxx", "ddooss"]}}

hash.each do |key, key2, value|
    puts key
    hash[key].each do |key, value|
        puts key
        hash[key][value].each do |value|
            puts value
        end
    end
end

1 个答案:

答案 0 :(得分:1)

解决方案

Hash#each中的块使用两个变量(|key,value|)进行迭代,Array#each中的块使用一个变量(|element|)进行迭代。

由于您具有嵌套的哈希值和数组,因此需要多次应用each,并使用不同的变量名称。 puts与缩进一起使用,以更好地显示结构:

hash = {1 => {"a1" => ["un", "uno"], "a2" => ["uunn", "uunnoo"]}, 2 => {"b1" => ["deux", "dos"], "b2" => ["ddeuxx", "ddooss"]}}

hash.each do |id, sub_hash|
  puts id
  sub_hash.each do |key, sub_array|
    puts "  #{key}"
    sub_array.each do |word|
      puts "    #{word}"
    end
  end
end

输出

1
  a1
    un
    uno
  a2
    uunn
    uunnoo
2
  b1
    deux
    dos
  b2
    ddeuxx
    ddooss

您的代码

这是您的代码,修改次数最少:

hash.each do |key1, value1|
    puts key1
    hash[key1].each do |key2, value2|
        puts key2
        hash[key1][key2].each do |value|
            puts value
        end
    end
end

请注意,hash[key1]实际为value1hash[key1][key2]value2