我有一个哈希数组:
[{"green" => 1, "red" => 2, "blue" => 3}, {"green" => 4, "red" => 5, "blue" => 6}]
我想选择红色、蓝色或绿色等于某个数字的哈希值。我该怎么做呢?
我有一个哈希数组:
[{"green" => 1, "red" => 2, "blue" => 3}, {"green" => 4, "red" => 5, "blue" => 6}]
我想选择红色、蓝色或绿色等于某个数字的哈希值。我该怎么做呢?
如果我正确地理解了你。
arr = [{"green" => 1, "red" => 2, "blue" => 3}, {"green" => 4, "red" => 5, "blue" => 6}]
some_number = 1
arr.select { |el| el.any? {|k,v| v == some_number} }
改良版:
arr.select { |el| a.has_value?(some_number) }
如果可能有更多不需要测试的键的版本(例如黄色):
arr = [{"green" => 1, "red" => 2, "blue" => 3, "yellow" => 5}, {"green" => 4, "red" => 5, "blue" => 6, "yellow" => 3}]
some_number = 1
fields_to_check = ["red", "green", "blue" ]
arr.select { |el| fields_to_check.any? {|color| el[color] == some_number } }
我会Hash#values_at
用来获取与您感兴趣的键关联的值数组:
arr = [{"green" => 1, "red" => 2, "blue" => 3}, {"green" => 4, "red" => 5, "blue" => 6}]
arr.select { |h| h.values_at("red", "green", "blue").include? 1 }
如果你想选择一个散列,如果任何键的值等于n
arr.select{|h| h.values.include? n}
选择指定键的值之一是否等于n
arr.select{|h| h.select{|k,v| ("red","green","blue").include? k && v == n}