find is an Enumerable method that searches an enumerable object and returns the first element whose block result is truthy. It stops immediately after a match; when no element passes the test, it returns nil. The synonymous name detect is also available. section 10.3.1
Find the first matching element
[1, 2, 3, 4, 5, 6, 7].find { |n| n > 5 } # => 6 find calls the block once per element, in order. The first truthy result wins, so iteration stops at 6 rather than continuing through the array. section 10.3.1
Several details make find useful in everyday collection code:
- Enumerable supplies find when a class defines each and includes Enumerable; find uses each to test yielded elements. section 10.1
- A failed search returns nil, so a search for an actual nil element is ambiguous: success and failure produce the same result. section 10.3.1
- Pass a Proc as the first argument to supply a fallback value or action when no element matches. section 10.3.1
- Use select or find_all when every matching element is needed, and reject when matching elements should be excluded. section 10.3.1
Listing 10.1 An Enumerable class and its deployment of the each method
class Rainbow
include Enumerable
def each
yield "red"
yield "orange"
yield "yellow"
yield "green"
yield "blue"
yield "indigo"
yield "violet"
end
end
A minimal Enumerable class shows how defining each enables find and other Enumerable methods. section 10.1



