Reputation: 1975
I have an array of hashes like this:
arr = [
{ email: '[email protected]', valid: true },
{ email: '[email protected]', valid: false }
]
I need to check if email: '[email protected]'
and valid: true
both exist in a single hash.
How can I check for such hash in the array without using each
loop?
Currently I am doing this:
found = false
arr.each do|v|
if v[:email] == '[email protected]' && v[:valid] == true
found = true
break
end
end
Upvotes: 3
Views: 289
Reputation: 168131
To check if a hash has all the key-value pairs that another hash has, use >
, <
, or their variants >=
, <=
. You can be assured that the order of key-value pairs does not matter.
arr.any?{|h| h >= {email: "[email protected]", valid: true}}
# => true
arr.any?{|h| h >= {valid: true, email: "[email protected]"}}
# => true
Upvotes: 7
Reputation: 23327
You can use Enumerable#any?
that does more or less what you did in your implementation:
> found = arr.any?{|e| e[:email] == '[email protected]' && e[:valid] }
=> true
Upvotes: 7