D
David A. Black
Hi --
Strictly speaking, it isn't shorthand for either, since there are
cases where the expansion will fail but ||= won't because x isn't
initialized. However, discounting that, the expansion is:
x || x = y
The only time this matters is with hashes that have default values. In
every other case, as far as I know, x = x || y also describes what's
happening. But the expansion which describes *every* case is x || x =
y.
I wrote a blog post about this recently:
http://dablog.rubypal.com/2008/3/25/a-short-circuit-edge-case
(I changed || to or for some reason, which screws up the precedence,
but I inserted corrections later.)
David
--
Rails training from David A. Black and Ruby Power and Light:
ADVANCING WITH RAILS April 14-17 New York City
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
See http://www.rubypal.com for details and updates!
Huh?
My understanding has always been that x ||= y is shorthand for x = x
|| y just as x += y is shorthand for x = x + y. That also seems to be
the understanding of the "Programming Ruby" text (p. 125 of the
latest). In other words, an assignment will take place even if it's
superfluous.
Strictly speaking, it isn't shorthand for either, since there are
cases where the expansion will fail but ||= won't because x isn't
initialized. However, discounting that, the expansion is:
x || x = y
The only time this matters is with hashes that have default values. In
every other case, as far as I know, x = x || y also describes what's
happening. But the expansion which describes *every* case is x || x =
y.
I wrote a blog post about this recently:
http://dablog.rubypal.com/2008/3/25/a-short-circuit-edge-case
(I changed || to or for some reason, which screws up the precedence,
but I inserted corrections later.)
David
--
Rails training from David A. Black and Ruby Power and Light:
ADVANCING WITH RAILS April 14-17 New York City
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
See http://www.rubypal.com for details and updates!