Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#find

find(if_none_proc = nil) {|element| ... } → object or nil
find(if_none_proc = nil) → enumerator

Returns the first element for which the block returns a truthy value.

With a block given, calls the block with successive elements of the collection; returns the first element for which the block returns a truthy value:

Example
(0..9).find {|element| element > 2}                # => 3

If no such element is found, calls if_none_proc and returns its return value.

Example
(0..9).find(proc {false}) {|element| element > 12} # => false
{foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') }            # => [:bar, 1]
{foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []

With no block given, returns an Enumerator.

See also #filter_map #find_all #filter #find_index also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0