title: How to memoize a class method with META PROGRAMMING?
body: <p>EDIT: To be clear.  This is a question about how to do something with meta programming.  It's not about memoizing.  Clearly there are better ways to memoize.  The relevant methods have "memoize" in them just to illustrate their purpose.</p>
  
  <hr>
  
  <p>I'm just toying around with meta programming, so please don't answer use a
  <code>@foo</code> instance variable.</p>
  
  <p>I have the following that tries to memoize both an instance and a class method
  by overwriting the method definition from the running method..</p>
  
  <pre><code>class Obj
    class &lt;&lt; self
  
      def meta_me; self; end
  
      def class_memoize
        puts "hard core calculating ..."
        abc = "huge calculation result"
  
        raise "broken here with infinite loop"
  
        define_class_method "class_memoize" do
          puts abc
          abc
        end
        class_memoize
      end
  
      def define_class_method name, &amp;blk
        meta_me.instance_eval do
          define_method name, &amp;blk
        end
      end
    end
  
    def instance_memoize
      puts "hard core calculating ..."
      abc = "huge calculation result"
  
      self.class.meta_me.send :define_method, :instance_memoize do
        puts abc
        abc
      end
  
      instance_memoize
    end
  end
  
  o = Obj.new
  o.instance_memoize
  # hard core calculating ...
  # huge calculation result
  
  o.instance_memoize
  # huge calculation result
  </code></pre>
  
  <p>The instance version works, but the class version does not.</p>
  
  <p>I've left in an attempt at the class version for reference.</p>