I’m trying to evaluate the expression (a=10) || (rr=20) while the rr variable is not defined
so typing rr in the ruby console before evaluating the previous expression returns
rr
NameError: undefined local variable or method `rr' for main:Object
from (irb):1
from :0
When I write the expression (a=10) || (rr=20) it returns 10, and when I write rr afterwards it says nil
(a=10) || (rr=20)
rr # => nil
so, why is this happening? Shouldn’t rr be defined only if the second argument of the || operator is evaluated, which should be never based on the documentation?
This happens because the ruby interpreter defines a variable when it sees an assignment to it (but before it executes the actual line of code). You can read more about it in this answer.
Boolean OR (
||) expression will evaluate to the value of left hand expression if it is notniland notfalse, else||will evaluate to the value of right hand expression.In your example the ruby interpreter sees an assignment to
aandrr(but it doesn’t execute this line yet), and initializes (defines, creates)aandrrwithnil. Then it executes the||expression. In this||expression,ais assigned to10and10is returned.r=20is not evaluated, andrris not changed (it is stillnil). This is why in the next linerrisnil.