The find_all/select methods take an enumerable collection return a new array of only the elements for which the given block returns true. It's the simplest way to filter a list in Ruby. select is most often used, though both aliases are acceptable.
- 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
@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8] # all even numbers: @numbers.select(&:even?) #=> [0, 2, 4, 6, 8] # all positive numbers: @numbers.select{|number| number >= 0} #=> [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]
Pet Inventory
# all pets with legs: @inventory.select{|pet| pet.legs > 0}.map(&:name) #=> ["dog", "cat", "scorpion", "beetle", "monkey"] # all pets in stock: @inventory.select(&:in_stock?).map(&:name) #=> ["dog", "cat", "fish", "scorpion", "beetle", "monkey"] # all pets with name: @inventory.select{|pet| !pet.name.nil?}.map(&:name) #=> ["dog", "cat", "fish", "scorpion", "beetle", "monkey", "rock"]
Pokey Things
# pokey things with at least 5 letters: @pokey_things.seek(0) @pokey_things.select{|line| line.chomp.size >= 5}.map(&:chomp) #=> ["cactus", "knife", "cactus holding poles with knives attached"] # pokey things with the letter 'e': @pokey_things.seek(0) @pokey_things.select{|line| line.include?('e')}.map(&:chomp) #=> ["pole", "knife", "cactus holding poles with knives attached"]
Heroku Log File
# all heroku requests made via the GET method: @requests.select(&:get?).map(&:id) #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31] # all heroku requests made via the POST method: @requests.select(&:post?).map(&:id) #=> [22]