On 2010-06-14 14:48:36 -0700, Roger Pack said:

> I read this once:
> 
> Operator ||= can be shorthand for code like:
>  x = "(some fallback value)" unless respond_to? :x or x
> 
> How would that look like exactly, in shorthand, any guesses?
> -r

The expression:

a ||= b

is equivalent to:

a || a = b

in most cases. To be pedantic, it is actually:

(defined?(a) && a) || a = b

and does not raise an error for undefined local variables. This is also 
true of `&&='.

Note:

The code:

x = "some value"

will *always* set the local variable `x', whether there is a method `x' 
on self or not, so your code that uses respond_to? will not behave as 
you expect it to.

Another note:

the expression (in pseudocode):

a <op>= b

is equivalent to:

a = a <op> b

except where <op> is || or &&, where the above applies.

Examples:

1)

a = 1
a += 5
a *= 10

a # => 60

2)

b = [:foo, :bar]
b |= [:bar, :bizz]

b # => [:foo, :bar, :bizz]

3)

flag = 0b01
flag |= 0b10
flag.to_s(2) # => "11"

-- 
Rein Henrichs
http://puppetlabs.com
http://reinh.com