Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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
like image 845
mechanicalfish Avatar asked Oct 29 '12 17:10

mechanicalfish


1 Answers

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.

like image 79
Holger Just Avatar answered Oct 12 '22 23:10

Holger Just