Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby select with multiple conditions

Tags:

ruby

I have an array of hashes:

[{"green" => 1, "red" => 2, "blue" => 3}, {"green" => 4, "red" => 5, "blue" => 6}]

I want to select the hash in which either red, blue or green is equal to a certain number. How would I go about doing this?

like image 214
Cristiano Avatar asked Jun 13 '26 02:06

Cristiano


2 Answers

If I understood You correctly.

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} }

Improved version:

arr.select { |el| a.has_value?(some_number) }

Version if there could be more keys that don't need to be tested (yellow in example):

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 } }
like image 198
Edgars Jekabsons Avatar answered Jun 15 '26 03:06

Edgars Jekabsons


I'd use Hash#values_at to get an array of the values associated with the keys you're interested in:

arr = [{"green" => 1, "red" => 2, "blue" => 3}, {"green" => 4, "red" => 5, "blue" => 6}]
arr.select { |h| h.values_at("red", "green", "blue").include? 1 }
like image 23
Stefan Avatar answered Jun 15 '26 02:06

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!