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.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
- Practice this method as an interactive kata on Codewars
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| !pet.name.nil?} #=> 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? @pokey_things.seek(0) # starting at the beginning of the file @pokey_things.all?{|line| line.size >= 3} #=> true # do all pokey things have the letter 'e'? @pokey_things.seek(0) # 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| request.host == 'example.herokuapp.com'} #=> true
There's one request that came via the POST method, so all? returns false. However, all requests were for the same host (domain).