36

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?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338

2 Answers2

53

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.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • I would change wording for "when you have two different local variables with the same name". To something in lines of "when you have local variable(s) with same name as another variable or method in outer scope". – Haris Krajina Jan 13 '14 at 13:00
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.

Tomasz Kowalczyk
  • 10,472
  • 6
  • 52
  • 68