title: I want to add a singleton method with a closure to a Ruby object
body: <p>I wish to add a singleton method to a particular object. I wish that when a instance method on a object is first called, it does some work, and then creates a singleton method for said object of the same name (that contains the work). On all subsequent calls on said object, the singleton method would shadow the instance method and would be called.</p>
  
  <p>I know how to create a singleton method, my problem is that I want the singleton method created to call a lambda (<code>l</code> in this case). def does not create a closure, so I cannot reference variable l (code below) when the method is subsequently called (<code>l.call()</code> is commented out in this example) I wish to know how I can create a closure when creating a singleton method on a particular object. Any help would be appreciated. Thank you.</p>
  
  <pre><code>class Thing
  end
  
  t = Thing.new
  t2 = Thing.new
  
  Thing.instance_eval() do
    def speak
      puts "I speak for all Things, I am a class method"
    end
  end
  
  Thing.class_eval() do
    def speak
      puts "This is the instance method referenced by the Thing object #{self}"
      r = "something I wish to hold on to, maybe expensive to calculate"
      l = lambda {puts r}
      instance_eval() do
        def speak()
          puts "This is the singleton method in the Thing object #{self}"
          #l.call() # I want this to work! How?
        end
      end
    end
  end
  
  Thing.speak()
  t.speak()
  t2.speak()
  t.speak()
  t2.speak()
  </code></pre>
  
  <p>Gives the following results when run: (I changed '&lt;' to '#' so they show up in html)</p>
  
  <blockquote>
    <p>I speak for all Things, I am a class
    method</p>
    
    <p>This is the instance method referenced
    by the Thing object #Thing:0x1d204></p>
    
    <p>This is the instance method referenced
    by the Thing object #Thing:0x1d1dc></p>
    
    <p>This is the singleton method in the
    Thing object #Thing:0x1d204></p>
    
    <p>This is the singleton method in the
    Thing object #Thing:0x1d1dc></p>
  </blockquote>