Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Official expansion of ||= conditional assignment operator

Tags:

ruby

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.

like image 859
cbmanica Avatar asked Sep 05 '12 18:09

cbmanica


People also ask

What does ||= mean in Ruby?

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.

What are the 3 conditional operators?

There are three conditional operators: && the logical AND operator. || the logical OR operator. ?: the ternary operator.

What is the symbol used for conditional 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.

Is ?: A conditional operator?

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.


1 Answers

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.

like image 176
luis24fps Avatar answered Sep 28 '22 06:09

luis24fps