all? Method

The all? method takes an enumerable collection and tests whether the given condition is true for every item in the collection. It returns true only if every element meets the condition.

Number List

First, the code:

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# are all numbers even?
@numbers.all?(&:even?)    #=> false

# are all numbers positive? 
@numbers.all?{|number| number >= 0}    #=> true

# if list is empty, is everything true?
p [].all?(&:even?)    #=> true

This last example is something I found interesting while playing with this method. If your list is empty, what does the all? method return? By default, it returns true because no items failed the comparison test. Technically, no items passed either, which is a bit confusing, but I guess the authors picked the default that would work as you expect most of the time.

Pet Inventory

# do all pets have legs?
@inventory.all?{|pet| pet.legs > 0}    #=> false

# are all pets in stock?
@inventory.all?(&:in_stock?)    #=> false

# all pets have a name? 
@inventory.all?{|pet| !}    #=> true

Let's walk through these examples. Do all pets have legs? No, fish and rocks don't pass the legs > 0 test. Are all pets in stock? No, we're out of pet rocks. Do all pets have a name? Yes, because no pet names are nil.

Pokey Things

# do all pokey things have at least 3 letters?  # starting at the beginning of the file
@pokey_things.all?{|line| line.size >= 3}    #=> true

# do all pokey things have the letter 'e'? # starting at the beginning of the file
@pokey_things.all?{|line| line.include?('e')}    #=> false

These examples are pretty straightforward - every pokey thing on our list has at least three letters, but "cactus" doesn't have an "e".

Heroku Log File

# were all heroku requests via the GET method?
@requests.all?(&:get?)    #=> false

# were all heroku requests for the same host?
@requests.all?{|request| == ''}    #=> true

There's one request that came via the POST method, so all? returns false. However, all requests were for the same host (domain).

Leave a Reply

Your email address will not be published. Required fields are marked *