You can't pass an anonymous function using the syntax you're using.  You =
can pass it as a lambda, something like:

[1,2,3].collect_until(lambda {|x| x%2 =3D=3D 0}) {|item| item + 10}

You could define collect_until like this:

class Array
  def collect_until(fn, &block)
    result =3D []
    self.each do |x|
      if !fn.call(x)
        result << (yield x)
      else
        break
      end
    end
    result
  end
end

I think the actual result would be only [11], since the collection would =
proceed UNTIL the value mod 2 was zero, which would happen at 2.  =
Therefore the processing would stop then.

steven

On Aug 27, 2010, at 12:32 AM, timr 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.
>=20
> 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:
>=20
> [1,2,3].collect{|item| item + 10} # =3D> [11,12,13]
> [1,2,3].collect_until({|x| x%2 =3D=3D 0}) {|item| item + 10} # =3D> =
[11,12]
>=20
> To get this to work the result from the yield to {|item| item + 10}
> block would be run through the {|x| x%2 =3D=3D 0} block to check if we =
are
> done.
>=20
> Thanks for any suggestions.
>=20