Ruby Parenthesis syntax exception with i++ ++i
Why does this throw a syntax error? I would expect it to be the other way around...
>> foo = 5
>> foo = foo++ + ++foo
=> 10 // also I would expect 12...
>> foo = (foo++) + (++foo) 开发者_如何转开发
SyntaxError: <main>:74: syntax error, unexpected ')'
foo = (foo++) + (++foo)
^
<main>:75: syntax error, unexpected keyword_end, expecting ')'
Tried it with tryruby.org which uses Ruby 1.9.2.
In C# (.NET 3.5) this works fine and it yields another result:
var num = 5;
var foo = num;
foo = (foo++) + (++foo);
System.Diagnostics.Debug.WriteLine(foo); // 12
I guess this is a question of operator priority? Can anybody explain?
For completeness...
C returns 10 Java returns 12There's no ++
operator in Ruby. Ruby is taking your foo++ + ++foo
and taking the first of those plus signs as a binary addition operator, and the rest as unary positive operators on the second foo
.
So you are asking Ruby to add 5 and (plus plus plus plus) 5, which is 5, hence the result of 10.
When you add the parentheses, Ruby is looking for a second operand (for the binary addition) before the first closing parenthesis, and complaining because it doesn't find one.
Where did you get the idea that Ruby supported a C-style ++
operator to begin with? Throw that book away.
Ruby does not support this syntax. Use i+=1
instead.
As @Dylan mentioned, Ruby is reading your code as foo + (+(+(+(+foo))))
. Basically it's reading all the +
signs (after the first one) as marking the integer positive.
Ruby does not have a ++
operator. In your example it just adds the second foo, "consuming" one plus, and treats the other ones as unary + operators.
精彩评论