declaratively caching results of a method

D

Daniel Berger

Sean said:
I should have pointed out that this method only memoizes within the
instance... Another instance of Foo won't get the benefit of the
memoization.

Sean

Eh? If you memoize in initialize, why wouldn't another instance of Foo get the
benefit?

Regards,

Dan
 
R

Ryan Leavengood

I'm debating between this suggestion and Pit's (where you access the cach= e via
it's name and as an instance method). I dunno - what do people prefer?

This one is certainly simpler :)

I prefer Pit's. Otherwise you'll have to hang on to each cache
yourself (should you memoize several methods), instead of just letting
the class do it.

Ryan
 
S

Sean O'Halpin

I prefer Pit's. Otherwise you'll have to hang on to each cache
yourself (should you memoize several methods), instead of just letting
the class do it.

Ryan

Agreed. Pit's is better (even if more complicated ;)

Sean
 
S

Sean O'Halpin

Eh? If you memoize in initialize, why wouldn't another instance of Foo ge= t the
benefit?

Try it:

class Foo
include Memoize
def initialize
memoize :foo
end
def foo(*args)
puts "calculating #{self}.foo(#{args.map{|x| x.inspect}.join(',')})"
args.inject(0) {|sum, x| sum + x}
end
end

f =3D Foo.new
puts f.foo(2)
puts f.foo(2)

g =3D Foo.new
puts g.foo(2)


__END__
calculating #<Foo:0x28705e8>.foo(2)
2
2
calculating #<Foo:0x28703d8>.foo(2)
2

It's because you're defining the memoized method on the singleton class:

(class << self; self; end).class_eval do ... end

Regards,

Sean
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,779
Messages
2,569,606
Members
45,239
Latest member
Alex Young

Latest Threads

Top