Why is `a = a` `nil` in Ruby?

我的梦境 提交于 2019-11-26 05:59:01

问题


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:


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.



来源:https://stackoverflow.com/questions/8908050/why-is-a-a-nil-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!