为什么Ruby不支持i ++或i-(增加/减少运算符)?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (42)

前/后增加/减少运算符(++--)是非常标准的编程语言语法(至少对于过程和面向对象的语言)。

为什么Ruby不支持它们?我知道你可以用+=和完成同样的事情-=,但排除类似的东西似乎很古怪,特别是因为它非常简洁和传统。

例:

i = 0    #=> 0
i += 1   #=> 1
i        #=> 1
i++      #=> expect 2, but as far as I can tell, 
         #=> irb ignores the second + and waits for a second number to add to i

提问于
用户回答回答于

http://blade.nagaokaut.ac.jp/ruby/ruby-talk/2710

Hi,

In message "[ruby-talk:02706] X++?"
    on 00/05/10, Aleksi Niemelä <aleksi.niemela@cinnober.com> writes:

|I got an idea from http://www.pragprog.com:8080/rubyfaq/rubyfaq-5.html#ss5.3
|and thought to try. I didn't manage to make "auto(in|de)crement" working so
|could somebody help here? Does this contain some errors or is the idea
|wrong?

  (1) ++ and -- are NOT reserved operator in Ruby.

  (2) C's increment/decrement operators are in fact hidden assignment.
      They affect variables, not objects.  You cannot accomplish
      assignment via method.  Ruby uses +=/-= operator instead.

  (3) self cannot be a target of assignment.  In addition, altering
      the value of integer 1 might cause severe confusion throughout
      the program.

                            matz.
用户回答回答于

一个原因是到目前为止,每个赋值操作符(即更改变量的操作符)都有一个赋值操作符=。如果添加++并且--不再是这种情况。

另一个原因是,行为++--经常混淆的人。例子:i++在你的例子中,返回值实际上是1,而不是2(然而,新i值将是2)。

扫码关注云+社区