Ruby为什么不支持i ++或i--(增减运算符)? [英] Why doesn't Ruby support i++ or i--​ (increment/decrement operators)?

查看:65
本文介绍了Ruby为什么不支持i ++或i--(增减运算符)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前/后递增/递减运算符(++--)是相当标准的编程语言语法(至少对于过程语言和面向对象的语言而言).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆