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?
This will do.
arr.all?(&:even?)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With