Skip to content
instance method

Enumerable#find

() { (Elem) -> ::boolish } -> Elem?
() -> ::Enumerator[Elem, Elem?]
[T] (::Enumerable::_NotFound[T] ifnone) { (Elem) -> ::boolish } -> (Elem | T)
[T] (::Enumerable::_NotFound[T] ifnone) -> ::Enumerator[Elem, Elem | T]
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.

Ruby version changes

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