On Thu, May 24, 2012 at 7:30 AM, Llelan D. <[email protected]> wrote:
> botp wrote in post #1061908:
>> return r if (r=foo)
>>
>> but ruby complains w(ith) undefined r
>
> This is a BUG!

No.  Local variables are defined from the location of their first
assignment.  Since the assignment comes _lexically_ after the test the
variable is undefined in the expression.  That's actually a pretty
well known property of the language - albeit a bit tricky at times.

> The expression after an IF does not define new scope, you're still in
> the containing scope. This means the initial statement of the
> if-modifier is validating the scope of any local variables before the
> if-modifier expression is evaluated.
>
> According to the "Ruby Standardization WG Draft August 25, 2010"
> Section 12.3 The if modifier statement
> Page 107
> ---------
> Semantics
>  An if-modifier-statement of the form S if E, where S is the statement
> and E is the expression,
>  is evaluated as follows:
>    a) Evaluate the if-expression of the form if E then S end.
>    b) The value of the if-modifier-statement is the resulting value.
> ---------
>
> The Semantics section item 'a' clearly states that the if-modifier
> should be interpreted in the same manner as the equivalent single-line
> if-expression. This means that the initial statement should not be
> validating local variables until after the modifier expression is
> evaluated, possibly initializing new local variables for use in the
> initial statement.

You are missing an important detail: local variable definition is done
at _parse time_.  It is purely syntactical and has nothing to do with
runtime evaluation.  What you call "validation of local variables" at
runtime does not exist.

> Please report this as an interpretor bug.

Please don't.

We're lucky because there is another idiom which fits the bill (I
won't go into lengthy explanations why I still consider assignments in
conditionals bad and only reasonable in loops):

r = foo and return r

Hint: different precedence of "and" compared to "&&" makes this
possible without the brackets that Matthew hat to use.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- You received this message because you are subscribed to the Google Groups 
ruby-talk-google group. To post to this group, send email to 
[email protected]. To unsubscribe from this group, send email 
to [email protected]. For more options, visit this 
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en

Reply via email to