Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Array#detect

() { (Elem) -> ::boolish } -> Elem?
() -> ::Enumerator[Elem, Elem?]
[T] (::Enumerable::_NotFound[T]? ifnone) { (Elem) -> ::boolish } -> (Elem | T)
[T] (::Enumerable::_NotFound[T]? ifnone) -> ::Enumerator[Elem, Elem | T]
detect(*args)

Alias of #find

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

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

Example
[1, 3, 5].find {|element| element > 2}                # => 3

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

Example
[1, 3, 5].find(proc {-1}) {|element| element > 12} # => -1

With no block given, returns an Enumerator.