且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在Ruby中`a = a` nil`?

更新时间:2022-05-07 01:03:49

Ruby解释器看到nil的赋值时,会使用nil初始化局部变量.它会在执行赋值表达式之前甚至在无法访问赋值时初始化局部变量(如下例所示).这意味着您的代码使用nil初始化a,然后表达式a = nil的值将为右手值.

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

第一个赋值表达式不执行,但anil初始化.

The first assignment expression is not executed, but a is initialized with nil.

您可以在Ruby 查看全文