How does that x ||= 1 work (for us newbies)?

-----Original Message-----
From: Dave Thomas [mailto:Dave / PragmaticProgrammer.com]
Sent: Monday, April 30, 2001 1:56 PM
To: ruby-talk / ruby-lang.org; ruby-talk / netlab.co.jp
Subject: [ruby-talk:14449] Re: How to do it the Ruby-way 1


Stefan Matthias Aust <sma / 3plus4.de> writes:

> Hi!
> 
> I'm still a Ruby newbie and wonder what is the best way to express the
> following algorithm in Ruby: A cache shall provide a service to access
> the contents of files so that files are read only once.
> 
> class Cache
>   @@cache = {}
>   def Cache.get(name)
>     cache.fetch(name) {@@cache[name] = File.open(name).read}
>   end
> end

A useful idiom is

    @@cache[name] ||= File.open(name).read

Regards


Dave