Simon Woker
Simon Woker

Reputation: 5034

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 12

Upvotes: 3

Views: 6598

Answers (3)

J-_-L
J-_-L

Reputation: 9177

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.

Upvotes: 6

kindall
kindall

Reputation: 184101

There'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.

Upvotes: 13

Jeremy
Jeremy

Reputation: 22415

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.

Upvotes: 13

Related Questions