I'm looking for a select
that "short-circuits" once it's returned a certain number of items:
>>> [1, 2, 3, 4, 5].select_first(1) { |x| x.odd? }
[1]
>>> [1, 2, 3, 4, 5].select_first(2) { |x| x.odd? }
[1, 3]
>>> [1, 2, 3, 4, 5].select_first(1000) { |x| x.odd? }
[1, 3, 5]
Is there a library function, either in core or in ActiveSupport, that does this? It's easy to roll my own, but I thought I would check.
Note that I do not want select { ... }.take(n)
because the block might have side effects.
You could do something along the lines of
But if you want to avoid
select{ . . }.take(n)
you could also do: