take_while method

The take_while method works very similarly to take; it takes an enumerable collection and returns the first several elements, for as long as each element returns true when passed to the given block. This is NOT like select - once the block returns false for an element, take_while stops looking and returns what it has so far.

Number List

def prime? number
  return true if number < 4
  (2...number).each do |factor|
    return false if number % factor == 0

@numbers = &#91;1, 0, 3, 2, 5, 4, 7, 6, 9, 8&#93;

# taking until we find an even number:

# taking until we find a non-prime number:
@numbers.take_while{|number| prime?(number)}

Pet Inventory

# taking until we find a pet with low inventory:
@inventory.take_while{|pet| pet.quantity >= 50}.map(&:name)

# taking until we find the first legless pet:
@inventory.take_while{|pet| pet.legs > 0}.map(&:name)

Pokey Things

# taking until we see a pokey thing with the letter 'f':
@pokey_things.take_while{|thing| !thing.include?('f')}.map(&:chomp)

# taking until a pokey thing has more than 7 letters:
@pokey_things.take_while{|thing| thing.chomp.length < 7}.map(&:chomp)

Heroku Log File

# taking until a request uses the POST method:
@requests.take_while{|request| request.method != 'POST'}.map(&:id)

# taking until a request is successful:
@requests.take_while{|request| request.error?}.map(&:id)

Leave a Reply

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