I want to emphasize I am looking for the actual way the ||=
operator is expanded by the Ruby 1.9.3 interpreter, not how it appears to be expanded based on its behavior. What I'm really hoping for is someone who has grokked the actual interpreter source, a task which I sadly am probably not up to. The only resource I have found that appears to examine this question is out of date: "A short-circuit (||=) edge case".
The resource I mentioned above seems to suggest that the "official" expansion of x ||= y
to x = x || y
was either inaccurate or buggy in interpreter versions prior to 1.9. In any case, the edge case indicated seems to have been smoothed out. The resource above claims that x || x = y
or x or x = y
are "more accurate". Neither of those, however, is correct, because they don't work when x
is a previously undeclared global variable:
[11:04:18][****@asha:~]$ irb
1.9.3-p194 :001 > a || a = 3
NameError: undefined local variable or method `a' for main:Object
1.9.3-p194 :002 > b or b = 3
NameError: undefined local variable or method `b' for main:Object
1.9.3-p194 :003 > c = c || 3
=> 3
So in 1.9.3, at least, the x = x || y
expansion appears to be correct, as far as these examples are concerned. However, to reiterate my original point, I would really like to see some truly authoritative source resolve this question, well, authoritatively rather than anecdotally as I (and others) have done.
In ruby 'a ||= b' is called "or - equal" operator. It is a short way of saying if a has a boolean value of true(if it is neither false or nil) it has the value of a. If not it has the value of b.
There are three conditional operators: && the logical AND operator. || the logical OR operator. ?: the ternary operator.
A conditional operator is represented by the symbol '?:'. The first operand (specified before the '?:') is the evaluating (conditional) expression. It has to be such that the type of evaluated expression can be implicitly converted to 'bool' or that implements operator true in order to avoid compilation errors.
The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows: The first operand is implicitly converted to bool . It is evaluated and all side effects are completed before continuing.
x ||= y
is a shorthand form for
x || x = y
If x
is not nil
and x
is not false
, the assignation will have place because of the short-circuit evaluation of the ||
operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With