From: Brian Candler Date: 2012-11-04T18:05:32+09:00 Subject: Re: bug?: local variable created in if modifier not available in modified expression Igor Pirnovar wrote in post #1082716: > Ignoring the confusing and to interpreter ambiguous syntax above, which > BTW can easily be fixed, we can see the problem in the code as written > is not that variables inside the conditional statement behave as block > local variable, or that in an assignment to a nonexistent variable > inside the conditional expression causes that variable to lose its > dynamic property, somehow turning it into a static variable in front of > the conditional expression! Please don't take any notice of this. There are no "static variables" or "dynamic variables" in Ruby. Neither does operator precedence have anything to do with this. It is simply this: Ruby decides what local variables exist in a method during a left-to-right parse of the code. At the first point that an assignment is seen, e.g. "foo = ...", then "foo" is created as a local variable - i.e. space is reserved for it on the stack frame - and from this point to the end of the block or method, a bareword "foo" is treated as an access to that local variable. However, you can still force a method call using foo() or self.foo >> def foo >> "Method foo" >> end => nil >> foo => "Method foo" >> foo = 123 if false => nil >> foo => nil >> foo() => "Method foo" >> self.foo => "Method foo" So at "foo = 123" onwards, bareword foo is a local variable. This occurs when the code is *parsed*, so it doesn't matter that the expression is never even executed. This rule is strictly left to right. Another example: >> def bar >> "Method bar" >> end => nil >> bar if bar = 123 (irb):4: warning: found = in conditional, should be == => "Method bar" The bar before the if is a method call bar(), because bar is only available as a local variable from the 'bar = 123' assignment onwards. So if you repeat this line, it changes its behaviour: >> bar if bar = 123 (irb):5: warning: found = in conditional, should be == => 123 That's all there is to it. -- Posted via http://www.ruby-forum.com/.