Why is `a = a` `nil` in Ruby?
Asked Answered
I

1

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
Illiberal answered 18/1, 2012 at 9:46 Comment(0)
S
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.

Sudduth answered 18/1, 2012 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.