I have an array, and I want the result of the first block that returns a truthy value (aka, not nil). The catch is that in my actual use case, the test has a side effect (I'm actually iterating over a set of queues, and pop'ing off the top), so I need to not evaluate the block beyond that first success.
a,b,c = [1,2,3]
[a,b,c].first_but_value{ |i| (i + 1) == 2 } == 2
a == 2
b == 2
c == 3
Any ideas?
break
is ugly =PIf you want a functional approach, you want a lazy map:
If you don't believe it is not iterating throughout the array, just print out and see:
Replace
i.to_s
by your block.I doubt there's a way to do this. The problem being that Ruby creates a closure in the block and the variable
i
is local to it. Doingi+=1
can be expanded toi = i + 1
which creates a new variablei
in the block's scope and doesn't modify the value in any of youra,b,c
variables.Here's my take, is this closer to your actual use case? Note the content of
b
is3
instead of2
becausemy_test_with_side_effect
is called onb
as well.find_yield
does what you want, check out ruby facets with many core extensions, and especiallyfind_yield
Enumberable method: https://github.com/rubyworks/facets/blob/master/lib/core/facets/enumerable/find_yield.rbIs this what you want to do?