On 05.01.2007 12:12, Andrew Stewart wrote: > > On 5 Jan 2007, at 09:05, Sam Kong wrote: > >> I find myself to use the following idiom frequently. >> >> def foo i >> return @cache[i] if @cache[i] >> @cache[i] = some_method_that_takes_long_time(i) >> end > > You could also use the 'overlooked feature of Ruby hashes' and put your > lengthy method in the block you pass to Hash.new: > > http://moonbase.rydia.net/mental/blog/programming/overlooked-feature-of-ruby-hashes.html That's definitively a better option - especially if i is non numeric. :-) def initialize @foo = Hash.new {|h,k| h[k] = some_method_that_takes_long_time(k)} end def foo(i) @foo[i] end Cheers robert