>> [1, 2, 3, 4, 5].any? {|n| n % 3 == 0}
=> true
What if I want to know which item matched, not just whether an item matched? I’m only interested in short-circuiting solutions (those that stop iterating as soon as a match is found).
I know that I can do the following, but as I’m new to Ruby I’m keen to learn other options.
>> match = nil
=> nil
>> [1, 2, 3, 4, 5].each do |n|
.. if n % 3 == 0
.. match = n
.. break
.. end
.. end
=> nil
>> match
=> 3
Are you looking for this:
From the docs:
So this would also fulfill your ‘short-circuiting’ requirement. Another, probably less common used alias for
Enumerable#findisEnumerable#detect, it works exactly the same way.