Flowdock
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} (that is all? will return true only if 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
Show source
Register or log in to add new notes.
August 15, 2008
4 thanks

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.

August 15, 2008
3 thanks

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.

August 15, 2008
1 thank

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:

  1. A two-element array, with the key in element 0 and its corresponding value in element 1, or

  2. Two separate items, the first being the key, the second being the corresponding value.