From: Tim Hunter Date: 2008-03-30T09:06:24+09:00 Subject: Re: Extrange behaviour using "if XXX ..." and "XXX if ..." I単aki Baz Castillo wrote: > El Domingo, 30 de Marzo de 2008, Tim Hunter escribi坦: > >> In case (b), there has not yet been an assignment before the reference >> to a, so Ruby assumes that "a" is a method call, yet there is no >> definition for a so you get the message. > > b) > a if a="QWEQWE" > NameError: undefined local variable or method `a' for main:Object > > > But why the first "a" is interpreted before the "if" stament? Imagine this > example: > > defined?a > => nil > a="BLABLA" if 2 == 3 > => nil > a > => nil > > After this code "a" will remain "nil" (or the previous value it had), so: > a="BLABLA" > hasn't been interpreted since the "if" stament failed. > > Also note this other example: > > defined?kk > => nil > kk if nil > => nil > > Why in this last case the code doesn't return: > "undefined local variable or method kk' " > ? > > I assume the reason: "kk" is not interpreted if the condition fails. > In b) the first "a" is then interpreted AFTER the condition success, so in > that moment "a" has been already declared (into the condition), so it would > exist and not give an error. > > Am I not right? > > > You must distinguish between parsing and execution. Ruby parses your program before Ruby executes your program. Ruby decides how to interpret the reference to a during parsing, before Ruby executes the if statements in your examples. Their success or failure has nothing to do with the decision. In this case a if a = "qweqwe" Remember parsing occurs from left to right. Ruby sees the reference to a to the left of the assignment to a. When Ruby first encounters a reference to a it assumes that since it has not yet seen any assigment to a, then a must be a method name. -- RMagick: http://rmagick.rubyforge.org/ RMagick 2: http://rmagick.rubyforge.org/rmagick2.html