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?
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.
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.
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.
#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.
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?)
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