arrays - ruby enumerables: is there a detect for results of block evaluation? -


i'm looking similar #detect in enumerables, not quite. enumerable does:

[1, 2, 3].detect {|i| > 1 } #=> 2 

it returns first instance of array matches condition. now, purpose return value of block. concern not conditions, instance, first not nil. this:

[var1, var2, var3].wanted_detect {|var| another_function(var) }  

in function return first result of another_function call isn't nil.

mapping values of applying method on variables , using detect not option. 1 ideally have work in lazy enumerators, mapping of possible values no-go

[var1, var2, var3].lazy.map { |var| another_function(var) }.compact.first 

if don't have access enumerable#lazy, easy enough implement want:

module enumerable   def wanted_detect     self.each |obj|       val = yield obj       return val if val     end   end end 

demo:

[1, 2, 3, 4].wanted_detect { |x| x*x if x > 2 } # => 9 

edit: sorry, missed last paragraph till falsetru pointed out.

thanks comments, falsetru.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -