为什么 Ruby 不支持 i++ 或 i-- (递增/递减运算符)? [英] Why doesn't Ruby support i++ or i-- (increment/decrement operators)?
问题描述
前/后自增/自减运算符(++
和 --
)是非常标准的编程语言语法(至少对于过程和面向对象的语言).
The pre/post increment/decrement operator (++
and --
) are pretty standard programing language syntax (for procedural and object-oriented languages, at least).
为什么 Ruby 不支持它们?我知道你可以用 +=
和 -=
完成同样的事情,但排除这样的东西似乎很奇怪,特别是因为它是如此简洁和传统.
Why doesn't Ruby support them? I understand you could accomplish the same thing with +=
and -=
, but it just seems oddly arbitrary to exclude something like that, especially since it's so concise and conventional.
示例:
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
我知道 Fixnum
是不可变的,但是如果 +=
可以实例化一个新的 Fixnum
并设置它,为什么不为++
?
I understand Fixnum
is immutable, but if +=
can just instanciate a new Fixnum
and set it, why not do the same for ++
?
包含 =
字符的作业的一致性是造成这种情况的唯一原因,还是我遗漏了什么?
Is consistency in assignments containing the =
character the only reason for this, or am I missing something?
推荐答案
这是 Matz(Yukihiro Matsumoto) 在旧 线程:
Here is how Matz(Yukihiro Matsumoto) explains it in an old thread:
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.
这篇关于为什么 Ruby 不支持 i++ 或 i-- (递增/递减运算符)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!