From: Pit Capitain Date: 2001-12-25T18:27:25+09:00 Subject: [ruby-talk:29410] Re: a better way? On 24 Dec 2001, at 3:57, Ron Jeffries wrote: > On Sun, 23 Dec 2001 03:48:19 GMT, nobu.nokada@softhome.net wrote: > > > class Temp > > @@save = Hash.new do |h, c| > > puts "Performing calculation...." > > h[c] = c * 9 / 5 + 32 > > end > > def fahrenheit(c) > > @@save[c] > > end > > end > > These are way cool. I gather the 1.7.2 feature is new? I think I'm in > 1.6 and it doesn't work there. On 1.6.x, you still can use the ||= assignment operator: class Temp @@save = {} def fahrenheit(c) @@save[c] ||= begin print "calculating... " c * 9 / 5 + 32 end end end t = Temp.new puts t.fahrenheit(100) # calculating... 212 puts t.fahrenheit(100) # 212 puts t.fahrenheit(300) # calculating... 572 If you omit the print statement, you even get the one-liner you originally wanted: class Temp @@save = {} def fahrenheit(c) @@save[c] ||= c * 9 / 5 + 32 end end t = Temp.new puts t.fahrenheit(100) # 212 puts t.fahrenheit(100) # 212 puts t.fahrenheit(300) # 572 Merry Christmas everybody, Pit