3

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Simon Woker
  • 4,994
  • 1
  • 27
  • 41
  • possible duplicate of [Why doesn't Ruby support i++ or i-- for fixnum?](http://stackoverflow.com/questions/3660563/why-doesnt-ruby-support-i-or-i-for-fixnum) – Andrew Grimm Oct 03 '11 at 23:04

3 Answers3

13

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.

kindall
  • 178,883
  • 35
  • 278
  • 309
12

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.

Jeremy
  • 22,188
  • 4
  • 68
  • 81
  • 1
    @Simon: It thinks you mean `foo + (+(+(+(+foo))))` (basically applying a positive sign to the second `foo` four times and adding it to the first `foo`). Ruby doesn't support `foo++` or `++foo`. – Dylan Markow Jun 28 '11 at 16:05
6

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.

kindall
  • 178,883
  • 35
  • 278
  • 309
J-_-L
  • 9,079
  • 2
  • 40
  • 37