Archive

Archive for November, 2011

memoize in Ruby

November 19, 2011 Leave a comment

Going thru this exercise really helped me gain some depth in ruby programming.  Take advantage of the metaprogramming & singleton classes.

#adapted from Dave Thomas's screencast on metaprogramming in Ruby

module Memoize
  def remember(name, &block)
 
    define_method(name, &block)
 
    orig = instance_method(name)
 
    mem = {}
    define_method(name) do |*args|
      if mem.has_key?(args)
        mem[args]
      else
        bound = orig.bind(self)
        mem[args] = bound.call(*args)
      end
    end
  end
end
 
class Finder
   extend Memoize
 
  remember :find do |*objs|
    expensive(*objs)
  end
 
  def expensive(*objs)
    puts "expensive"
    objs.inject{|m,n| m + n }
  end
end

 
#test it
d = Finder.new
puts d.find(1,2,3)
puts d.find(1,2,3) #expensive is not called here
Categories: tech Tags: ,
%d bloggers like this: