This may be a simple ruby question, but I was quite surprised by this, and not sure of a workaround.
I wanted to capture the state of a Fixnum within a lambda at it's declaration, and I'm finding that's not possible. For example: [1] pry(main)> index = 10 => 10 [2] pry(main)> e = lambda do [2] pry(main)* puts index [2] pry(main)* end => #<Proc:0x000000020b9580@(pry):2 (lambda)> [3] pry(main)> e.() 10 => nil [4] pry(main)> index += 10 => 20 [5] pry(main)> e.() 20 # This result is expected. We're looking directly at index => nil [6] pry(main)> f = lambda do [6] pry(main)* current = index [6] pry(main)* end => #<Proc:0x00000002001980@(pry):8 (lambda)> # Now I *assume* at this point, the block would essentially take the value of index, and assign it to 'current', but seemingly, it does not. Which I find odd. [7] pry(main)> f.() => 20 [8] pry(main)> index += 10 => 30 [9] pry(main)> f.() => 30 # and here I'm expecting 20, but I'm not. The actual code in question looks something akin to (cut down for brevity) index = 0 shape.points.each_by do |x, y| image_render_queue << lambda do render_image(image[index], x, y) end index += 1 end #by the time it gets here, index == shape.points.size rather than each value. image_render_queue.each(&:call) x and y are captured for each lambda, but not the index value. This leaves me kinda confused. That and Fixnum doesn't have a .dup .. so I'm no way to force it to be passed by value. So any help here would be useful! Thanks! :) Clearly I'm missing something, I've just not sure what. (and I could also refactor this to not use lambdas, but I'm curious as to what the issue is anyway). Cheers, Mark -- E: [email protected] T: http://www.twitter.com/neurotic W: www.compoundtheory.com 2 Devs from Down Under Podcast http://www.2ddu.com/ -- You received this message because you are subscribed to the Google Groups "Ruby or Rails Oceania" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rails-oceania?hl=en.
