From: Benoit Daloze Date: 2010-08-24T02:52:48+09:00 Subject: Re: Your thoughts on #memo ? On 23 August 2010 17:18, Intransition wrote: > Like to get some thoughts on the following technique for memoization: > >  # Memoize a method. >  # >  #   class MemoExample >  #     attr_accessor :a >  #     def m >  #       memo{ @a } >  #     end >  #   end >  # >  #   ex = MemoExample.new >  # >  #   ex.a = 10 >  #   ex.m  #=> 10 >  # >  #   ex.a = 20 >  #   ex.m  #=> 10 >  # >  def memo(&block) >    key = eval('__method__', block) >    val = block.call >    singleton_class = (class << self; self; end) >    singleton_class.__send__(:define_method, key){ val } >    val >  end > > Downside / upsides to the approach? Any suggestions for improvement? > Or is this just an altogether bad idea? > > It looks a bit weird, and eval is really ugly^ I recently wrote two crazy implementations of memoize: http://github.com/eregon/project_euler/blob/master/014.rb#L64-93 The second seems rather inefficient, while the first seems good. I'm here saving the only argument to determine what to cache. It is pretty bad because it redefines the method, however all the meta-programming stuff is rather interesting, I think. What do you think of it? B.D.