I
Intransition
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?
# 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__
val
end
Downside / upsides to the approach? Any suggestions for improvement?
Or is this just an altogether bad idea?