Home > Back-end >  Check if multiple key-value pairs exist in a Ruby hash?
Check if multiple key-value pairs exist in a Ruby hash?

Time:01-28

I have the following Ruby hash key-value pairs:

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

What I need to check is see if the following key-value pairs are both present:

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

Essentially wanting something to the effect of...

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

CodePudding user response:

If you are using ruby >= 2.3, there is a fancy new Hash >= Hash operation that is conceptually similiar to a hypothetical contains?

Using your traits array:

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

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

So you could try something like:

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

CodePudding user response:

We have the aptly named all? and any? methods that should do exactly what you're looking for.

All we need to do is loop through your filter_traits hash and test to see if all (or any) those key:value pairs are equal to (==) any corresponding key:value pairs inside your traits array:

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
  •  Tags:  
  • Related