all?
all?()
public
Passes each element of the collection to the given block. The method returns true if the block never returns false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } which will cause #all? to return true when none of the collection members are false or nil.
%w[ant bear cat].all? { |word| word.length >= 3 } #=> true %w[ant bear cat].all? { |word| word.length >= 4 } #=> false [nil, true, 99].all? #=> false
Using all? on Empty Arrays and Hashes
When applied to an empty array or hash, with or without a block, all? always returns true. That’s because with an empty collection, there are no values to process and return a false value. so, watch out, if your array or hash is empty for any reason you will get a true which might not be what you expect it to be.
Testing Arrays for nils with Enumerable#all?
When the block is omitted, all? uses this implied block: {|item| item}.
Since everything in Ruby evaluates to true except for false and nil, using all? without a block on an array is effectively a test to see if all the items in the collection evaluate to true (or conversely, if there are any false or nil values in the array).
Using all? without a block on a hash is meaningless, as it will always return true.
Enumerable#all? and Hashes
When used on a hash and a block is provided, all? passes each key/value pair as a two-element array to the block, which you can “catch” as either:
-
A two-element array, with the key in element 0 and its corresponding value in element 1, or
-
Two separate items, the first being the key, the second being the corresponding value.