From: Robert Klemme Date: 2013-02-16T23:30:38+09:00 Subject: Re: Fun with finalizers On Sat, Feb 16, 2013 at 12:08 PM, Garthy D wrote: > Excellent thinking. I also thought it might be something along those lines > too. To make it crystal clear: the reason is that there is a closure involved. The closure will hold on to the object referenced by a on method entry - unless, as you discovered, that reference is cleared. Just in case and if you don't know, here's what a closure does: irb(main):015:0> def f; x=0; lambda { x+=1 } end => nil irb(main):016:0> g = f => # irb(main):017:0> g.call => 1 irb(main):018:0> g.call => 2 irb(main):019:0> g.call => 3 The closure captures the current scope, i.e. all local variables. This includes method arguments and "self" - and hence all member variables of self as well: irb(main):023:0> def f; @x = 0; lambda { @x += 1 } end => nil irb(main):024:0> g = f => # irb(main):025:0> g.call => 1 irb(main):026:0> g.call => 2 irb(main):027:0> g.call => 3 irb(main):028:0> g.call => 4 > I tried various combinations as well: proc, Proc.new, I think a return > from method(), calls to a separate object; but there was no impact on the > result. If "a" isn't cleared, the object is held. I would be surprised if there was. lambda and Proc both create a closure. Difference between lambda and Proc are in a different area: http://stackoverflow.com/questions/1740046/whats-the-difference-between-a-proc-and-a-lambda-in-ruby > I'm guessing that there > might be some way to say to not touch a thing in the current scope, but I'm > not sure *how* to specify it. There is no way to exclude that variable from the closure - other than not passing it. But that would be pointless here. :-) > I also adapted the main program based on my experience with the code below, > and suddenly the finalizers were called. So it's the same type of problem. > > So there's a problem, and it's avoidable. I know the "what", but don't know > the "why". There is some subtlety I'm missing. Most interesting. :) Now you should know. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/