Narfanator Narfanator - 1 year ago 61
Ruby Question

Ruby - Array.find, but return the value the block

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?

Answer Source
[1, 2, 3].each{|i| i += 1; break i if i == 2} 
# => 2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download