any? Method

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

Number List

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

# are any numbers even?
@numbers.any?(&:even?)    #=> true

# are any numbers negative?
@numbers.any?{|number| number < 0}    #=> false

# if list is empty, is anything true?
[].any?(&:even?)    #=> false

Unilke the all? method, calling any? on an empty collection will return false. This is because the method is looking for at least one true value to be returned, and it receives none.

Pet Inventory

# do any pets have three legs?
@inventory.any?{|pet| pet.legs == 3}    #=> false

# are any pets sold out?
@inventory.any?(&:sold_out?)    #=> true

# do any pets have a quantity of just one? 
@inventory.any?{|pet| pet.quantity == 1}    #=> true

Just like with our simple number list, any? is looking for at least one true result after executing the given block on every item in the collection.

Pokey Things

# do any pokey things have at least 5 letters?
@pokey_things.seek(0) # starting at the beginning of the file
@pokey_things.any?{|line| line.size >= 5}    #=> true

# are pillows on the list of pokey things?
@pokey_things.seek(0) # starting at the beginning of the file
@pokey_things.any?{|line| line.include?('pillow')}    #=> false

We do have a couple pokey things with at least five letters, so our first test passes. The word "pillow", however, doesn't appear in any part of our list, not even as part of a larger phrase. This makes sense - even if you're building a complicated poking device, pillows are never going to add value to the equation.

Heroku Log File

# do any heroku requests result in error?
@requests.any?(&:error?)    #=> true

# are there any missing page errors?
@requests.any?{|request| request.status == 404}    #=> false

The only error we have in our log file is this one:

2014-09-03T00:02:08.867841+00:00 heroku[router]: sock=client at=error code=H18 desc="Request Interrupted" method=GET path="/" host=example.herokuapp.com request_id=6148cfb4-0128-4ce6-93b6-03f8f9afb932 fwd="173.190.161.172" dyno=web.1 connect=1ms service=1458ms status=503 bytes=785

which deals with an interrupted request, not a missing page.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>