Ruby Parenthesis syntax exception with i++ ++i

后端 未结 3 643
野趣味
野趣味 2021-01-14 17:05

Why does this throw a syntax error? I would expect it to be the other way around...

>> foo = 5
>> foo = foo++ + ++foo                                     


        
3条回答
  •  梦毁少年i
    2021-01-14 17:12

    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.

提交回复
热议问题