“阴影"是什么意思在 Ruby 中是什么意思? [英] What does "shadowing" mean in Ruby?

查看:95
本文介绍了“阴影"是什么意思在 Ruby 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我明白了

warning: shadowing outer local variable - x

大概与使用 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?

推荐答案

阴影是当您有两个同名的不同局部变量时.据说在内部作用域中定义的变量隐藏"了外部作用域中的变量(因为只要内部变量在作用域内,外部变量现在就不再可访问,即使否则它会在作用域内).

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).

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

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.

这篇关于“阴影"是什么意思在 Ruby 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆