I
Intransition
This method has long been suggested to me as #map_detect. At first I
wasn't sure of it's usefulness. But now I think it's okay. (Your
thoughts?). In any case, the name has to go. Currently I'm thinking
#find_yield. Any better suggestions?
module Enumerable
# Similar to #detect and #find. Yields each element to the block
# and returns the first result that evaluates as *true*,
# terminating early.
#
# obj1.foo? #=> false
# obj2.foo? #=> true
# obj2.foo #=> "value"
#
# [obj1, obj2].find_yield { |obj| obj.foo if obj.foo? } #=>
"value"
#
# If the block is never true, return the +fallback+ parameter,
# or nil if no +fallback+ is specified.
#
# [1,2,3].find_yield { |_| false } #=> nil
# [false].find_yield(1) { |_| false } #=> 1
#
def find_yield(fallback = nil) #:yield:
each do |member|
result = yield(member)
return result if result
end
fallback
end
end
Thanks.
wasn't sure of it's usefulness. But now I think it's okay. (Your
thoughts?). In any case, the name has to go. Currently I'm thinking
#find_yield. Any better suggestions?
module Enumerable
# Similar to #detect and #find. Yields each element to the block
# and returns the first result that evaluates as *true*,
# terminating early.
#
# obj1.foo? #=> false
# obj2.foo? #=> true
# obj2.foo #=> "value"
#
# [obj1, obj2].find_yield { |obj| obj.foo if obj.foo? } #=>
"value"
#
# If the block is never true, return the +fallback+ parameter,
# or nil if no +fallback+ is specified.
#
# [1,2,3].find_yield { |_| false } #=> nil
# [false].find_yield(1) { |_| false } #=> 1
#
def find_yield(fallback = nil) #:yield:
each do |member|
result = yield(member)
return result if result
end
fallback
end
end
Thanks.