From: Michael Edgar Date: 2011-07-30T08:03:43+09:00 Subject: Re: avoiding capturing local variables in closures On Jul 29, 2011, at 5:48 PM, Chuck Remes wrote: > def some_callback(bigarg1, bigarg2) > foo = transform(bigarg1) > bar = transformagain(bigarg2) > > schedule_for_execution { baz(foo, bar) } > end > > If I am understanding things correctly, the block passed to #schedule_for_execution is capturing the variables foo, bar, bigarg1 and bigarg2. I could avoid capturing bigarg1 and bigarg2 with a small refactoring. > > def some_callback(bigarg1, bigarg2) > foo = transform(bigarg1) > bar = transformagain(bigarg2) > > avoid_capture(foo, bar) > end > > def avoid_capture(foo, bar) > schedule_for_execution { baz(foo, bar) } > end > > Is this sufficient to avoid capturing those args in the closure? If not, what do I need to do? That should be sufficient - there's no more reference to some_callback's environment where bigarg1 and bigarg2 are referenced. Another approach might be, on 1.9: def some_callback(bigarg1) foo = transform(bigarg1) schedule_for_execution { |;bigarg1| bad(foo) } end This is the only real reason I know of for using the Ruby 1.9 block-local syntax. As long as the implementation is smart enough not to foolishly store bigarg1. Michael Edgar adgar@carboni.ca http://carboni.ca/