Enumerable Procs?

Hi Folks,

Is there any way to get something like this to work?

class Proc
    def to_ary(ct)
            a = []
            l = lambda { |x|
                    a << x
                    ct -= 1
                    break if ct == 0
            }
            call(&l)
            return a
    end
end

p lambda {
        yield 1
        yield 2
        yield 3
        yield 4
        yield 5
        yield 6
        yield 7
}.to_ary(5)

# would like this to be [1, 2, 3, 4, 5]

Thanks,

--Joe

···

--
Joe Edelman

Joe Edelman wrote:

Is there any way to get something like [Proc#call with an attached
block] to work?

Not in Ruby 1.8, because Procs don't have a block slot there. E.g. you
can't do lambda { yield }.call { puts "foo" }. This does however work
in Ruby 1.9.

Until then you might be able to work around your problem by not using
yield (you could pass a callback to the block) or not using a Proc.

class Proc
   def to_ary(ct)
     a =
     l = lambda { |x|
       return if ct == 0
       a << x
       ct -= 1
     }
     call(l)
     return a
   end
end

p proc { |yld|
   yld.call 1
   yld.call 2
   yld.call 3
   yld.call 4
   yld.call 5
   yld.call 6
   yld.call 7
}.to_ary(5)

T.