On Thu, Aug 26, 2010 at 11:32 PM, timr <timrandg / gmail.com> wrote:
> I am wondering if anyone has implemented an Array#collect_until method
> to break out of a collect loop after an end-point has been achieved
> during an Array#collect call.
>
> For instance, you have a long array of items and want to use each item
> to calculate something, but should the calculation give a specific
> result, then you know you are done--no need for processing the rest of
> the array. However, if that specified result is not met, the
> processing continues. Something like below:
>
> [1,2,3].collect{|item| item + 10} # => [11,12,13]
> [1,2,3].collect_until({|x| x%2 == 0}) {|item| item + 10} # => [11,12]
>
> To get this to work the result from the yield to {|item| item + 10}
> block would be run through the {|x| x%2 == 0} block to check if we are
> done.
>
> Thanks for any suggestions.
>
>

I know you already got something that works, but I think this is a
problem where enumerators provide an elegant solution:

module Enumerable
  def through
    Enumerator.new do |yielder|
      self.each do |val|
        yielder.yield(val)
        break if yield val
      end
    end
  end
end

then:

[1,2,3].through {|x| x % 2 == 0}.collect {|item| item+10} => [11,12]