Ruby Parenthesis syntax exception with i++ ++i

后端 未结 3 644
野趣味
野趣味 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-14 17:26

    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.

    0 讨论(0)
  • 2021-01-14 17:30

    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.

    0 讨论(0)
提交回复
热议问题