What does "shadowing" mean in Ruby?
If I do the following with warnings turned on under 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 do开发者_C百科es "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).
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.
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.
精彩评论