drop_while method

The drop_while method takes an enumerable collection and a block, skips elements until the given block returns true, and then returns the rest of the collection.

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]

# skipping until we find an even number:
@numbers.drop_while(&:odd?)
    #=> [0, 3, 2, 5, 4, 7, 6, 9, 8]


# skipping until we find a non-prime number:
@numbers.drop_while{|number| prime?(number)}
    #=> [4, 7, 6, 9, 8]

Pet Inventory

# skipping until we find a pet with low inventory:
@inventory.drop_while{|pet| pet.quantity >= 50}.map(&:name)
    #=> ["scorpion", "beetle", "monkey", "rock"]

# skipping until we find the first legless pet:
@inventory.drop_while{|pet| pet.legs > 0}.map(&:name)
    #=> ["fish", "scorpion", "beetle", "monkey", "rock"]

Pokey Things

# skipping until we see a pokey thing with the letter 'f':
@pokey_things.seek(0)
@pokey_things.drop_while{|thing| !thing.include?('f')}.map(&:chomp)
    #=> ["knife", "cactus holding poles with knives attached"]

# skipping until a pokey thing has more than 7 letters:
@pokey_things.seek(0)
@pokey_things.drop_while{|thing| thing.chomp.length < 7}.map(&:chomp)
    #=> ["cactus holding poles with knives attached"]

Heroku Log File

# skipping until a request uses the POST method:
@requests.drop_while{|request| request.method != 'POST'}.map(&:id)
    #=> [22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

# skipping until a request is successful:
@requests.drop_while{|request| request.error?}.map(&:id)
    #=> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

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>