迭代哈希数组的值

时间:2014-03-10 12:44:28

标签: ruby hash

我有一些哈希像:

AWARD = [ 
         {'KARMA_POINTS' => %w(initiate apprentice knight ace guardian sage master grand_master)},
         {'MICROBLOGS_POSTED' => %w(uno_plus)},
         {'COMMENTS_POSTED' => %w(first_responder)},
         {'IDEAS_POSTED' => %w(aryabhatta newton einstein)}
       ]

如果密钥的值与给定哈希值(AWARD)中的特定密钥匹配,则需要迭代密钥的值。

任何建议和解决方案将不胜感激。

2 个答案:

答案 0 :(得分:1)

这就是你想要的:

AWARD.each do |hash|
   # I used Hash#[] method. This method will return key if found, or nil.
   # As `nil` treated as falsy in Ruby, on nil **unless** block wouldn't be executed,
   # otherwise it will.
   unless hash['match_key'].nil?
     # I am calling here `Hash#each` method.
     hash.each do |key,value|
       value.each do |elem| # as values are Array, so calling Array#each
         # your code
       end
     end
   end
end

答案 1 :(得分:0)

迭代数组中的每个Hash。对于每个Hash,迭代每个key =>值对。对于每个key =>值对,做你的事。

AWARD = [ 
  {'KARMA_POINTS' => %w(initiate apprentice knight ace guardian sage master grand_master)},
  {'MICROBLOGS_POSTED' => %w(uno_plus)},
  {'COMMENTS_POSTED' => %w(first_responder)},
  {'IDEAS_POSTED' => %w(aryabhatta newton einstein)}
]

AWARD.each do |hash|
  hash.each do |key,value|
    value.each do |item| 
      # your code here
      puts item 
    end
  end
end