使用ruby散列作为从较大散列中进行选择的约束

时间:2012-02-24 22:33:48

标签: ruby hash

我有一个conditions哈希:

{"age" => "52", "First_Name" => "Bat"}

我有一系列person哈希:

[{"id"=>"1", "First_Name"=>"John", "Last_Name"=>"Doe", "Age"=>"27"}, {"id"=>"2", "First_Name"=>"Jane", "Last_Name"=>"Doe", "Age"=>"26"}, {"id"=>"3", "First_Name"=>"Bat", "Last_Name"=>"Man", "Age"=>"52"}, {"id"=>"4", "First_Name"=>"Bat", "Last_Name"=>"Woman", "Age"=>"51"}]

如何获取匹配person的所有conditions哈希值? (在这种情况下,它应该只返回“蝙蝠侠”哈希。)

1 个答案:

答案 0 :(得分:10)

如果您想所有匹配conditions的人

people.select do |person|
  conditions.all? { |k,v| person[k] == v }
end

或者,如果你确定只会有一个(感谢@tokland):

people.detect do |person|
  conditions.all? { |k,v| person[k] == v }
end