Ruby’esque Method Caching

October 30th, 2006

I am in love with how dynamic Ruby is… Whenever I talk about that aspect of Ruby I always bring up this example, which I heard about from someone that read it on the Ruby-talk mailing list. Nevertheless, doing it always amuses me.

So here we go. What I am going to do is make a Ruby class with an instance method and instance variable. The method first assigns the current time to an instance variable. Simple enough…but then I reopen the method and define it to just return that instance variable. What this ends up being is a simple form of caching:

class Cacher
def cache
@time=Time.now
def cache
‘Succesfully cached at: ‘ + @time.to_s
end
end
end

So now I can do this:

larry-diehls-computer:~ larrytheliquid$ irb
irb(main):001:0> require ‘cacher’
=> true
irb(main):002:0> c=Cacher.new
=> #
irb(main):003:0> c.cache
=> nil
irb(main):004:0> c.cache
=> “Succesfully cached at: Mon Oct 30 23:31:26 EST 2006″
irb(main):005:0> c.cache
=> “Succesfully cached at: Mon Oct 30 23:31:26 EST 2006″
irb(main):006:0> c.cache
=> “Succesfully cached at: Mon Oct 30 23:31:26 EST 2006″
irb(main):007:0> c.cache
=> “Succesfully cached at: Mon Oct 30 23:31:26 EST 2006″
irb(main):008:0>

As you can see, the @cache@ method gets redefined and always outputs the same thing. This works great for any method that takes a long time to execute but needs to be called multiple times. Say, maybe a Google Map API call, an intensive SQL statement, etc…

I love how simple this example is and plan to post plenty other such examples that illustrate the elegance of Ruby in the future, so stay tuned. Have something short and similar? You are most welcome to post it, or a link to your blog post about it, etc in the comments!

Leave a Reply