Hi --

On Thu, 5 Oct 2006, 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.
>
> Wasteful Example:
> class Foo
>  def c1
>    tmp1 = ExpensiveObject.new
>    tmp2 = ExpensiveObject.new
>    # stuff involving tmp1/tmp2
>    result = tmp1 + tmp2 + c2
>  end
>  def c2
>    tmp1 = ExpensiveObject.new
>    tmp2 = ExpensiveObject.new
>    # stuff involving tmp1/tmp2
>    result = tmp1 + tmp2
>  end
> end
>
> 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)( )

You could do:

   class Foo
     def initialize
       tmp1, tmp2 = EO.new, EO.new
       define_method("c1") { do stuff with tmp1 etc. }
       tmp1, tmp2 = EO.new, EO.new
       define_method("c2") { do stuff with tmp1 etc. }
     end
   end

or something like that.  I'd be inclined to revisit the instance
variable version, though.  I'm at the bottom of the well of mental
energy right now or I'd try to come up with a twist on it that might
seem less coupled....


David

-- 
                   David A. Black | dblack / wobblini.net
Author of "Ruby for Rails"   [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog)        [2] | Co-director, Ruby Central, Inc.   [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com    | [4] http://www.rubycentral.org