Conditional assignment
by Paweł Świątkowski
22 Aug 2014
The other day I was pair-programming with my boss and he wrote something along the lines of:
‘Whoa!’ I protested. ‘This ain’t gonna work as foo
might be not defined.’ Soon enough he proved me wrong by typing in the console:
I was a bit surprised and tried to explain this by assuming that somehow inline condition is binding stronger than assignment (we knew that if false; end
returns nil
). But then how would I explain what happens below?
I would not. I had to turn to Google and I found this Stack Overflow answer. Long story short, it turns out that before actual interpretation Ruby parser scans the code and when it comes across an assignment to a not-yet-defined variable, it defines it with allocating memory for it. The actual assigment may never happen, because interpreter never reaches this particular line of code, but the variable is defined and has a value of nil
nevertheless.
This is a weird side-effect and luckily happens only in given scope. See:
It also seems to be a reason for famous undefined_var = undefined_var
returning nil
.
Achtung!
Before you start using it around, please note that this effect does not exist in Rubinius (I tested with version 2.2.10).
However, x = x
when x has not been initialized still works.
JRuby behaves the same way as MRI.