Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 601
Narfanator Avatar asked Jul 23 '14 02:07

Narfanator


People also ask

What does array each return Ruby?

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.

How do you access an array of objects in Ruby?

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.

What does .first mean in Ruby?

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.

How do you find the subset of an array in Ruby?

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.


1 Answers

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.

like image 76
ribamar Avatar answered Oct 22 '22 09:10

ribamar