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 does "shadowing" mean?
In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope.
Declaring a variable with a name that already refers to another variable is called shadowing. In this case, you shadow a function argument.
How to avoid variable shadowing? To modify a global variable, and avoid variable shadowing python provides global keyword which tells python to use the global version of the variable, instead of creating a new locally scoped variable.
Just as a reminder: A variable, method, or type is said to shadow another variable, method, or type of the same name when it is declared in an inner scope, making it impossible to refer to the outer-scope entity in an unqualified way (or, sometimes, at all). Scala, just like Java, allows shadowing.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With