William James wrote:
> Joel VanderWerf wrote:
>> Gavin Sinclair wrote:
>>> On Jan 14, 1:34 am, "Trans" <transf... / gmail.com> wrote:
>>>>   def x
>>>>     return_on @cache[:x]
>>>>     # do stuff
>>>>     @cache[:x] = result_of_stuff
>>>>   end
>>>>
>>> def x
>>>   @cache[:x] ||= begin
>>>     # do stuff
>>>   end
>>> end
>> Or (saving an exception handler setup):
>>
>> def reverse x
>>    @cache[:x] ||= (
>>      puts "CACHING"
>>      x.reverse
>>    )
>> end
>>
>> @cache = {}
>>
>> p reverse("foo")
>> p reverse("foo")
>>
>> __END__
>>
>> Output:
>>
>> CACHING
>> "oof"
>> "oof"
> 
> It doesn't work correctly.
> 
> def reverse x
>    @cache[:x] ||= (
>      puts "CACHING"
>      x.reverse
>    )
> end
> 
> @cache = {}
> 
> p reverse("foo")
> p reverse("what?")
> p reverse("And this is cached, you think???")
> 
> ---  output  -----
> CACHING
> "oof"
> "oof"
> "oof"
> 

Oof! Typo.

def reverse x
   @cache[x] ||= (
     puts "CACHING"
     x.reverse
   )
end

@cache = {}

p reverse("foo")
p reverse("bar")
p reverse("foo")
p reverse("bar")

__END__

Output:

CACHING
"oof"
CACHING
"rab"
"oof"
"rab"

-- 
        vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407