I watched this video. Why is a = a
evaluated to nil
if a
is not defined?
我看了这段视频。如果a没有定义,为什么a = a被赋值为nil ?
a = a # => nil
b = c = q = c # => nil
1 个解决方案
#1
56
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.
Ruby解释器在看到赋值时,用nil初始化一个本地变量。它在执行赋值表达式之前或甚至当赋值不可达时(如下面的示例所示)初始化局部变量。这意味着你的代码用nil初始化a,然后表达式a = nil将计算到右边的值。
a = 1 if false
a.nil? # => true
The first assignment expression is not executed, but a
is initialized with nil
.
第一个赋值表达式不是执行的,而是用nil初始化的。
#1
56
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.
Ruby解释器在看到赋值时,用nil初始化一个本地变量。它在执行赋值表达式之前或甚至当赋值不可达时(如下面的示例所示)初始化局部变量。这意味着你的代码用nil初始化a,然后表达式a = nil将计算到右边的值。
a = 1 if false
a.nil? # => true
The first assignment expression is not executed, but a
is initialized with nil
.
第一个赋值表达式不是执行的,而是用nil初始化的。