liveBook · Manning

Find

As explained in The Well-Grounded Rubyist, Fourth Edition

find, also known as detect, is an Enumerable method that returns the first element for which its block evaluates truthily, or nil when no element matches.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains block evaluation, early termination, nil ambiguity, fallback Procs, and contrasts with multi-result selectors.
Examples
Uses a numeric array search, a nil-element search, a fallback lambda, and a custom Rainbow enumerable.
What it assumes
Assumes familiarity with arrays, blocks, truthiness, and iteration; demonstrates Enumerable behavior through each.
What you can do after
Apply it to return the first matching element, detect absence through nil, or provide a fallback Proc.
How it connects
Connects Enumerable and each with detect, select, find_all, reject, include?, and Proc objects.

Also explained in

Compare how 4 books explain find →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.