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?
Array#each returns the [array] object it was invoked upon: the result of the block is discarded. Thus if there are no icky side-effects to the original array then nothing will have changed.
In Ruby, there are several ways to retrieve the elements from the array. Ruby arrays provide a lot of different methods to access the array element. But the most used way is to use the index of an array.
The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.
slice() is a method in Ruby that is used to return a sub-array of an array. It does this either by giving the index of the element or by providing the index position and the range of elements to return.
break
is ugly =P
If you want a functional approach, you want a lazy map:
[nil, 1, 2, 3].lazy.map{|i| i && i.to_s}.find &:itself # => "1"
If you don't believe it is not iterating throughout the array, just print out and see:
[nil, 1, 2, 3].lazy.map{|i| (p i) && i.to_s}.find &:itself # nil # 1 # => "1"
Replace i.to_s
by your block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With