检查 Ruby 哈希中是否存在多个键值对?

Check if multiple key-value pairs exist in a Ruby hash?

我有以下 Ruby 个散列键值对:

[
   {
      "trait_type"=>"Status", 
      "value"=>"Unbuilt", 
      "display_type"=>nil, 
      "max_value"=>nil, 
      "trait_count"=>4866, 
      "order"=>nil
   }
]

我需要检查的是以下键值对是否存在:

{
   "value"=>"Unbuilt", 
   "trait_type"=>"Status"
}

本质上想要一些东西...

traits = [{"trait_type"=>"Status", "value"=>"Unbuilt", "display_type"=>nil, "max_value"=>nil, "trait_count"=>4866, "order"=>nil}]
filter_traits = {"value"=>"Unbuilt", "trait_type"=>"Status"}

traits.include? filter_traits

如果您使用的是 ruby >= 2.3,则有一个奇特的新 Hash >= Hash 操作在概念上类似于假设的 contains?

使用您的 traits 数组:

trait = traits[0]
trait >= {"trait_type" => "Status", "value" => "Unbuilt"}
# => true

trait >= {"trait_type" => "Status", "value" => "Built"}
# => false

所以你可以尝试这样的事情:

traits.select{|trait|
  trait >= filter_traits
}.length > 0
# => true

我们也有恰当命名的 all?any? 方法,它们应该以非常合乎逻辑的方式完全满足您的需求。

我们需要做的就是遍历您的 filter_traits 哈希并测试是否所有(或任何)这些 key:value 对等于 (==) 任何对应的 key:value 对在你的 traits 数组中:

traits = [{"trait_type"=>"Status", "value"=>"Unbuilt", "display_type"=>nil, "max_value"=>nil, "trait_count"=>4866, "order"=>nil}]
filter_traits = {"value"=>"Unbuilt", "trait_type"=>"Status"}

filter_traits.all? {|k, v| filter_traits[k] == traits[0][k]}
#=>  true

filter_traits = {"value"=>"Built", "trait_type"=>"Status"}
filter_traits.all? {|k, v| filter_traits[k] == traits[0][k]}
#=>  false

filter_traits.any? {|k, v| filter_traits[k] == traits[0][k]}
#=>  true
arr = [
   {
      "trait_type"=>"Status", 
      "value"=>"Unbuilt", 
      "display_type"=>nil, 
      "max_value"=>nil, 
      "trait_count"=>4866, 
      "order"=>nil
   }
]
h1 = { "value"=>"Unbuilt", "trait_type"=>"Status" }
h2 = { "value"=>"Rebuilt", "trait_type"=>"Status" }

这里有三种解决方案。

arr[0].slice(*h1.keys) == h1
  #=> true
arr[0].slice(*h2.keys) == h2
  #=> false

arr[0].values_at(h1.keys) == h1.values
  #=> true
arr[0].values_at(h2.keys) == h2.values
  #=> false

arr[0] == arr[0].merge(h1)
  #=> true
arr[0] == arr[0].merge(h2)
  #=> false