Why is `a = a` `nil` in Ruby?
I watched this video. Why is a = a
evaluated to nil
if a
is not defined?
a = a # => nil
b = c = q = c # => nil
Solution 1:
Ruby interpreter initializes a local variable with nil
when it sees an assignment to it. It initializes the local variable before it executes the assignment expression or even when the assignment is not reachable (as in the example below). This means your code initializes a
with nil
and then the expression a = nil
will evaluate to the right hand value.
a = 1 if false
a.nil? # => true
The first assignment expression is not executed, but a
is initialized with nil
.
You can find this behaviour documented in the Ruby assignment documentation.