From: Igor Pirnovar Date: 2012-11-04T16:08:18+09:00 Subject: Re: bug?: local variable created in if modifier not available in modified expression Mean L. wrote in post #1082083: > (local1 if local1 = "created") is supposed to be equivalent to > (if local1 = "created" then local1 end) > > but the later works as expected and the former does not. 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! Neither of these assumptions is correct. The reason, you did not get the results as you expected is because you are not taking account, that the conditional in this situation is executed last, since it has the lowest precedence of all operators, the only operator with lower precedence is the block expression (begin/end). The same is true for all conditional keywords {{ if, until, while, unless }}, and you can expect they behave in the same way as 'if'. In the following code you can see that neither is it true that variables before the conditional behave as static variables nor, are the variables inside the conditional expression, local to some invisible block: 1. p "v1:#{v1||='Not created' if ((v1='created')!='')}" #=> v1:created 2. p "v2:#{v2||='Not CREATED' if (v2='created') != ''}" #=> v2:created 3. p "if:#{if (v3 = 'created') != ''; v3; "XYZ"; end}" #=> if:XYZ 4. p "v3:#{v3}" #=> v3:created 5. p "v4:#{if (v4 = 'created') != ''; v4; end}" #=> v4:created 6. p "v5:#{v5 if ((v5='created')!='')}" #=> FAILS Lines number 3 and 5 above show that a conditional expression 'if' returns the value of the last expression in its block expression. However, when a conditional expression is used as modifier, obviously, there is no return value there, and line #6 fails with: `
': undefined local variable or method `v5' \ for main:Object (NameError) You can salvage this situation by delaying the access to 'v5' variable, by using v5||='Not created' idiom, which proves, that variable 'v5' comes from inside the 'if' expression, and is indeed, the dynamically created 'v5' rather than local static variable that shadows the temporary inner conditional-block's 'v5'. Regards, igor -- Posted via http://www.ruby-forum.com/.