Why x = x does not raise an error even if x is undefined

ruby

Solution

This is caused by the way variables are initialized in Ruby, which is rather unique to this language. Basically, Ruby initializes (creates) a variable if it could possibly get assigned a value. Consider this example:

if false
  x = "hello"
end

`x` will definitely not get assigned the `"hello"` string here. However, it will still get initialized with `nil` as from the static program analysis, it could have been assigned.

Your example is similar. Because you assign something to `x`, it will get initialized with `nil` before the statement is executed. Thus, during execution, `x` is in fact `nil`.

Problem

Possible Duplicate: Why is `a = a` `nil` in Ruby? I'm sure there is a reason for this behavior i'm just curious what it is. ``` y = x # NameError: undefined local variable or method 'x' x = x # => nil ```

Original source

Related problems