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

Hmm then again....

  require 'facet/annotation'

  class Foo

    ann :c1, :tmp1 => ExpensiveObject.new,
                  :tmp2 => ExpensiveObject.new

    def c1
      result = ann.c1.tmp1 + ann.c1.tmp2 + c2
    end

    ann :c2, :tmp1 => ExpensiveObject.new,
                  :tmp2 => ExpensiveObject.new

    def c2
      result = ann.c2.tmp1 + ann.c2.tmp2
    end

  end

Works as long ExpensiveObject isn't dependent on instance context.
(Note: If anyone actually tries this it may need to use:
'self.class.ann.c1.tmp1' instead, although it ought to work as given.)

T.