Reputation: 3717
I'm trying to write one line of code to tell me if there is an element in an array that meets a set of criteria and then breaks on true.
For example
I have [1,2,3,4,5,6,7,8,9,10,11,12]
and I want to find the first element that is divisible by 2 and 3. I want to write a one liner that will return true as soon as it hits 6 and not process the remaining elements in the array.
I can write a for each loop and break, but I feel like there should be a way to do that in one line of code.
Upvotes: 1
Views: 198
Reputation: 44110
any?
:
[1,2,3,4,5,6,7,8,9,10,11,12].any?{|e| e % 2 == 0 && e % 3 == 0}
or you can combine it with all?
and have a great tutorial example:
[1,2,3,4,5,6,7,8,9,10,11,12].any?{|e| [2, 3].all?{|d| e % d == 0}}
And if you actually need the first matching element returned, use find
:
[1,2,3,4,5,6,7,8,9,10,11,12].find{|e| [2,3].all?{|d| e % d == 0}}
# => 6
Upvotes: 5
Reputation: 31097
You should use: find
[1,2,3,4,5,6,7,8,9,10,11,12].find{|e| e % 2 == 0 && e % 3 == 0}
It will return 6, and it won't process the values after 6.
Upvotes: 4