43

I watched this video. Why is a = a evaluated to nil if a is not defined?

a = a # => nil
b = c = q = c # => nil

1 Answer 1

65

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.