From: Stefano Crocco Date: 2007-07-02T03:38:59+09:00 Subject: Re: Newbie Question. eval.rb variable scope issue Alle domenica 1 luglio 2007, Rishel,Wes ha scritto: > ��������ruby> var = " abc " > �������� � " abc " > ��������ruby> "1234#{var}5678" > �������� � "1234 abc 5678" > > On my machine eval.rb gives a different result. > > ��������ruby> var = " abc " > ����������������" abc " > ��������ruby> "1234#{var}5678" > ����������������ERR: undefined local variable or method `var' for > main:Object > ��������ruby> I don't know why you're getting this behaviour. On my system (linux, ruby 1.8.6 p36), the example works correctly: ruby> var = " abc " " abc " ruby> "1234#{var}5678" "1234 abc 5678" > Looking at the scoping rules for Ruby it is hard to understand how > eval.rb was ever able to perform the examples in the tutorial, since the > current output is entirely consistent with the scoping rule. It is also > hard to perceive how one could write a version of eval.rb that would > work, given that it pretty much has to have a loop. Here, I think you're wrong. The Pickaxe first edition states it clearly in the "Expressions" chapter (section "Variable scope and loops"): "The while, until, and for loops are built into the language and do not introduce new scope; previously existing locals can be used in the loop, and any new locals created will be available afterward." This is different from what happens with blocks, where variables created inside the block aren't accessible outside them. Since eval.rb uses a while loop, instead, variables defined in one iteration are kept in the following. Stefano