MxyL MxyL - 6 months ago 17
Ruby Question

Return true only if all values evaluate to true in Ruby

What's a fast way to verify whether all elements of an enumerable satisfy a certain condition? I guess logically it would be like:

elements = [e1, e2, e3, ...]
return (condition on e1) && (condition on e2) && (condition on e3) && ...


For example, if I had an array of integers, and I wanted to answer the question "Are all integers odd?"

I can always iterate over each value, check whether it's true, and then return false when one of them returns false, but is there a better way to do it?

Answer

You can use the all? function from the Enumerable mix-in.

elements = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
return elements.all? { |elem| elem % 2 != 0 }

Or, as pointed out in the comments, you could also use odd? if you're looking specificially for odd values.

elements = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
return elements.all?(&:odd?)
Comments