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
  end
  
  true
end

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

# taking until we find an even number:
@numbers.take_while(&:odd?)
    #=> 

# 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.seek(0)
@pokey_things.take_while{|thing| !thing.include?('f')}.map(&:chomp)
    #=> 

# taking until a pokey thing has more than 7 letters:
@pokey_things.seek(0)
@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 *

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>