Reputation: 795
I have a big array and I need to know whether all its elements are divisible by 2.
I'm doing it this way, but it's sort of ugly:
_true = true
arr.each { |e| (e % 2).zero? || _true = false }
if _true == true
# ...
end
How to do this without extra loops/assignments?
Upvotes: 8
Views: 3548
Reputation: 46667
Ruby's got you covered.
if arr.all? {|e| (e % 2).zero?}
There's also any?
if you need to check whether at least one element has a given property.
Upvotes: 18