The detect/find methods are the same. If you use Rails, it's preferable to use detect to distinguish from ActiveRecord's find method. It takes an enumerable collection and finds the first element for which the given block returns true.
- 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] # first even number: @numbers.detect(&:even?) #=> 0 # first number divisible by three: @numbers.detect{|number| number % 3 == 0} #=> 0
Pet Inventory
# first pet with four legs: @inventory.detect{|pet| pet.legs == 4}.name #=> dog no_pet = Pet.new('none', 0, 0) # first pet with 3 legs: " @inventory.detect(lambda{no_pet}){|pet| pet.legs == 3}.name #=> none
Pokey Things
first pokey thing with at least 3 letters: @pokey_things.seek(0) @pokey_things.map(&:chomp).detect{|word| word.size >= 3} #=> "cactus" first pokey thing with the letter 'e': @pokey_things.seek(0) @pokey_things.detect{|line| line.include?('e')} #=> "pole"
Heroku Log File
# first heroku request made via the POST method: @requests.detect(&:post?).id #=> 22 # first heroku request with error: @requests.detect{|request| request.error?}.id #=> 1