I'm looking for a method comparable to javascript's Array.prototype.every method but in ruby. In javascript, it iterates over the array and returns true if every element causes the callback to return true. One of the nice things about it is it doesn't bother iterating over the whole array if one of the elements fails the test. Instead it short-circuits and returns false.
function isBigEnough(element) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); //=> false
[12, 54, 18, 130, 44].every(isBigEnough); //=> true
I know I could get a similar effect with lower level iterators like the while loop.
def isBigEnough(arr)
i = 0
result = true
while i < arr.length
if arr[i] >= 10
i++
else
i = arr.length
result = false
end
end
return result
end
is_big_enough([12, 5, 8, 130, 44]) #=> false
is_big_enough([12, 54, 18, 130, 44]) #=> true
But I figured ruby would have something for this. Anyone know how to get this same effect?
all?method.