Method: Enumerable#find_yield

Defined in:
lib/core/facets/enumerable/find_yield.rb

#find_yield(fallback = nil) ⇒ Object Also known as: map_detect

Yield each element to the block and return the result of the block when that result evaluates as true, terminating early like #detect and #find.

obj1 = Object.new
obj2 = Object.new

def obj1.foo?; false; end
def obj2.foo?; true ; end

def obj1.foo ; "foo1"; end
def obj2.foo ; "foo2"; end

[obj1, obj2].find_yield{ |obj| obj.foo if obj.foo? }  #=> "foo2"

Another example.

[1,2,3,4,5].find_yield{ |i| j = i+1; j if j % 4 == 0 }  #=> 4

If the block is never true, return the object given in the first parameter, or nil if none specified.

[1,2,3].find_yield{ |_| false }    #=> nil
[false].find_yield(1){ |_| false } #=> 1


28
29
30
31
32
33
34
# File 'lib/core/facets/enumerable/find_yield.rb', line 28

def find_yield(fallback=nil) #:yield:
  each do |member|
    result = yield(member)
    return result if result 
  end
  fallback
end