What does “shadowing” mean in Ruby?

前端 未结 2 1582
孤街浪徒
孤街浪徒 2020-12-08 19:34

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: sh         


        
相关标签:
2条回答
  • 2020-12-08 19:56

    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.

    0 讨论(0)
  • 2020-12-08 20:03

    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.

    0 讨论(0)
提交回复
热议问题