Scope of a local variable in ruby
In ruby, only class, module and method can introduce new scope (see Ruby FAQ). Even if ruby has "if .. end", "while ... end" constructs, unlike c/c++/java/c#, they won't create new scope.
For example:
While there might be other motivations for this design, I think it is most likely driven by a technical issue: as I wrote before, ruby's lexer need to distinguish local variable and method call(command). It is easy for it to check "module", "class" and "def" keyword to recognize a new scope. However, as for "if", "while" etc (may followed by a complex expression), it is too hard for the lexer to handle (requires serious parsing capability).
For example:
if true
x = "hello"
end
# we can access x outside of "if". This will print "hello".
puts x
While there might be other motivations for this design, I think it is most likely driven by a technical issue: as I wrote before, ruby's lexer need to distinguish local variable and method call(command). It is easy for it to check "module", "class" and "def" keyword to recognize a new scope. However, as for "if", "while" etc (may followed by a complex expression), it is too hard for the lexer to handle (requires serious parsing capability).
0 Comments:
Post a Comment
<< Home