On 2009-12-31, Phillip G. [email protected] wrote:
Hm, on Ruby 1.9.1 I get:
irb(main):001:0> puts nil or 4
=> 4
Note that this is equivalent to “puts nil” followed by “4”.
That’s significant.
Consider:
irb(main):001:0> x = nil or 4
=> 4
irb(main):002:0> x
=> nil
The grouping is:
(x = nil) or (4)
Or
(puts nil) or (4)
This seems like a bug to me, since parenthesis should “only” make
method calls and precedent unambigious.
I believe that’s precisely the problem – the precedence of “or” is
low enough that it can’t occur inside a method argument.
Compare this with the similar situation in C, where a comma operator
cannot occur inside an argument list for a function, because it’s part
of the function-call syntax. So:
valid C:
x = 1, y = 2;
(this performs both assignments, and returns the value of y after the
assignment, which happens to be 2.)
printf(“%d\n”, x = 1, y = 2);
This probably prints 1, but I think it’s undefined behavior because
there’s
excess arguments to printf. (I’m not sure whether that’s permitted or
not,
but my guess would be “no, but it probably always works”.)
So try:
irb(main):003:0> puts( (nil or 4) )
4
=> nil
Basically, if you really want parentheses (as in the precedence-changing
operator), you need to include them… Not merely put something that
can’t
go in a method argument list inside the confusingly-similar-looking
() which surround method arguments.
-s