Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

hash

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
like image 583
Shpigford Avatar asked Jun 01 '26 15:06

Shpigford


1 Answers

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
like image 148
jamiew Avatar answered Jun 04 '26 11:06

jamiew