On Thu, Oct 05, 2006 at 08:18:24AM +0900, Gavin Kistner wrote:
> Because I just had to solve this problem in both JavaScript and Lua, and
> because I love Ruby more than either, I thought I'd ask people here how
> they'd solve it in Ruby.
> 
> The general question is: how would do you associate a few object
> instances with methods on a per-method basis?
>  
> The Situation/Requirements
> --------------------------
> A class has 2 different methods.
> Each method needs a couple 'scratch' objects to perform its
> calculations.
> The methods call each other; they must not use the same scratch objects.
> It is expensive to instantiate a scratch object.
> It's not expensive to initialize an existing scratch object with data.
> We like OOP coding, and want to call these as methods of a receiver.
> 
> Lua Solution #1: Closures (would work for JS, too)
> --------------------------------------------------
> Foo.c1 = ( function( )
>   local tmp1 = ExpensiveObject:new( )
>   local tmp2 = ExpensiveObject:new( )
>   return function( self )
>     -- stuff using tmp1 and tmp2
>   end
> end)( )
> 
> 
Can't you do the same here?

class A
 tmp1 = ExpensiveObject.new
 tmp2 = ExpensiveObject.new
 define_method(:c1) do # Look ma! a closure
   # stuff using tmp1 and tmp2
 end
end