Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "shadowing" mean in Ruby?

Tags:

ruby

shadow

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?

like image 998
Andrew Grimm Avatar asked Jun 06 '11 23:06

Andrew Grimm


People also ask

What is shadowing in programming?

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.

What is shadowing a parameter?

Declaring a variable with a name that already refers to another variable is called shadowing. In this case, you shadow a function argument.

How do you avoid variable shadowing?

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.

What is shadowing in Scala?

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.


2 Answers

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.

like image 185
sepp2k Avatar answered Sep 27 '22 21:09

sepp2k


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.

like image 26
Tomasz Kowalczyk Avatar answered Sep 27 '22 19:09

Tomasz Kowalczyk