Today’s Ruby Tuesday is on Enumerable#find a.k.a. Enumerable#detect.
Enumerable#find
takes a predicate as a block and returns the first item for which the predicate returns true. If the predicate doesn’t return true for any of the items in the enumeration, nil
is returned.
[1, 2, 3, 4, 5, 6, 7, 8, 9].find {|x| x > 5} # => 6 [1, 2, 3, 4, 5, 6, 7, 8, 9].find {|x| x > 15} # => nil
Enumerable#find
can also take a “callable” as an argument, which will be called to if no item matches the predicate, and use that result as the return value of Enumerable#find
.
[1, 2, 3, 4, 5, 6, 7, 8, 9].find(-> {:oops}) {|x| x > 15} # => :oops [1, 2, 3, 4, 5, 6, 7, 8, 9].find(-> {:oops}) {|x| x > 5} # => 6 [1, 2, 3, 4, 5, 6, 7, 8, 9].find(-> {[true, false].sample}) {|x| x > 15} # => false [1, 2, 3, 4, 5, 6, 7, 8, 9].find(-> {[true, false].sample}) {|x| x > 15} # => true [1, 2, 3, 4, 5, 6, 7, 8, 9].find(-> {[true, false].sample}) {|x| x > 15} # => false
–Proctor