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.
- 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
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) #=>