Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return true only if all values evaluate to true in Ruby

Tags:

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?

like image 973
MxLDevs Avatar asked May 20 '12 06:05

MxLDevs


People also ask

How do you check if all values in an array are equal Ruby?

How do you check if all elements in an array are equal Ruby? Ruby arrays may be compared using the ==, <=> and eql? methods. The == method returns true if two arrays contain the same number of elements and the same contents for each corresponding element.

What does .first mean in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.

What does all do in Ruby?

The all?() of enumerable is an inbuilt method in Ruby returns a boolean value true if all the objects in the enumerable satisfies the given condition, else it returns false. If a pattern is given, it compares with the pattern, and returns true if all of them are equal to the given pattern, else it returns false.

Does each return an array Ruby?

#Each and #Map They will both iterate (move through) an array, but the main difference is that #each will always return the original array, and #map will return a new array. create a new object with each: #each_with_object is a useful method that lets you add to a given object during each iteration.


1 Answers

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?)
like image 89
Makoto Avatar answered Sep 25 '22 00:09

Makoto