“影子”在Ruby中意味着什么?

时间:2021-02-04 22:34:46

If I do the following with warnings turned on under Ruby 1.9:

如果我在Ruby 1.9下打开警告时执行以下操作:

$VERBOSE = true
x = 42
5.times{|x| puts x}

I get

我明白了

warning: shadowing outer local variable - x

Presumably it's to do with using x as a block parameter as well as a variable outside of the block, but what does "shadowing" mean?

据推测,这与使用x作为块参数以及块外的变量有关,但“阴影”是什么意思?

2 个解决方案

#1


48  

Shadowing is when you have two different local variables with the same name. It is said that the variable defined in the inner scope "shadows" the one in the outer scope (because the outer variable is now no longer accessible as long as the inner variable is in scope, even though it would otherwise be in scope).

阴影是指两个具有相同名称的不同局部变量。据说内部范围中定义的变量“遮蔽”外部范围中的变量(因为只要内部变量在范围内,外部变量现在就不再可访问,即使它在其他范围内也是如此)。

So in your case, you can't access the outer x variable in your block, because you have an inner variable with the same name.

因此,在您的情况下,您无法访问块中的外部x变量,因为您有一个具有相同名称的内部变量。

#2


10  

Shadowing is more general term, it is applicable outside the Ruby world too. Shadowing means that the name you use in an outer scope - x = 42 is "shadowed" by local one, therefore makes in non accessible and confusing.

阴影是更通用的术语,它也适用于Ruby世界之外。阴影意味着您在外部范围中使用的名称 - x = 42由本地范围“遮蔽”,因此使其无法访问和混淆。

#1


48  

Shadowing is when you have two different local variables with the same name. It is said that the variable defined in the inner scope "shadows" the one in the outer scope (because the outer variable is now no longer accessible as long as the inner variable is in scope, even though it would otherwise be in scope).

阴影是指两个具有相同名称的不同局部变量。据说内部范围中定义的变量“遮蔽”外部范围中的变量(因为只要内部变量在范围内,外部变量现在就不再可访问,即使它在其他范围内也是如此)。

So in your case, you can't access the outer x variable in your block, because you have an inner variable with the same name.

因此,在您的情况下,您无法访问块中的外部x变量,因为您有一个具有相同名称的内部变量。

#2


10  

Shadowing is more general term, it is applicable outside the Ruby world too. Shadowing means that the name you use in an outer scope - x = 42 is "shadowed" by local one, therefore makes in non accessible and confusing.

阴影是更通用的术语,它也适用于Ruby世界之外。阴影意味着您在外部范围中使用的名称 - x = 42由本地范围“遮蔽”,因此使其无法访问和混淆。