Suppose I have an array of values [a,b,c,d,…] and a function f(x,…) which returns true or false.
[1,2,3,4].map {|x| f(x)} => [true true false true]
First, what is the best way to collapse the resultant list into a true or false value (via AND)? Is there a function that would allow me to map:
[true true false true]
to:
((true && true) && false) && true
using a cumulative pair-wise application of the binary && operator?
In this case the cost of evaluating the function is substancial, so would like to use a lisp-style “and” to evaluate the arguments (function applications) sequentially until one of them is false. Determined that could do:
!![1,2,3,4].each {|x| break false if !f(x) }
Which is ugly. Hoping that there is a more elegant way to do this. I am aware that I could add a new comprehension to Array, but hoping that there is something built-in that does this better. Thanks
You’re looking for
Enumerable#all?, which returns true if all of the invocations of its block are truthy. There is alsoEnumerable#any?, which returns true if any of the invocations of its block are truthy:any?short-curcuits: the first truthy value causes it to return true. So doesall?short circuit: the first falsy value causes it to return false.