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.
- 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] # 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]