Builtin Ruby or ActiveSupport function for "select first n elements satisfying a predicate"?

41 views Asked by At

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.

1

There are 1 answers

2
Sara Fuerst On BEST ANSWER

You could do something along the lines of

[1, 2, 3, 4, 5].lazy.select{|x| x.odd? }.take(n).to_a

But if you want to avoid select{ . . }.take(n) you could also do:

[1, 2, 3, 4, 5].each{|x| arr << x if x.odd?; break if arr.count == n}