Why doesn't Ruby support i++ or i— (increment/

2019-01-01 05:24发布

The pre/post increment/decrement operator (++ and --) are pretty standard programing language syntax (for procedural and object-oriented languages, at least).

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.

Example:

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

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?

9条回答
梦该遗忘
2楼-- · 2019-01-01 06:02

One reason is that up to now every assignment operator (i.e. an operator which changes a variable) has a = in it. If you add ++ and --, that's no longer the case.

Another reason is that the behavior of ++ and -- often confuse people. Case in point: The return value of i++ in your example would actually be 1, not 2 (the new value of i would be 2, however).

查看更多
伤终究还是伤i
3楼-- · 2019-01-01 06:03

Couldn't this be achieved by adding a new method to the fixnum or Integer class?

$ ruby -e 'numb=1;puts numb.next'

returns 2

"Destructive" methods seem to be appended with ! to warn possible users, so adding a new method called next! would pretty much do what was requested ie.

$ ruby -e 'numb=1; numb.next!; puts numb' 

returns 2 (since numb has been incremented)

Of course, the next! method would have to check that the object was an integer variable and not a real number, but this should be available.

查看更多
一个人的天荒地老
4楼-- · 2019-01-01 06:17

It's not conventional in OO languages. In fact, there is no ++ in Smalltalk, the language that coined the term "object-oriented programming" (and the language Ruby is most strongly influenced by). What you mean is that it's conventional in C and languages closely imitating C. Ruby does have a somewhat C-like syntax, but it isn't slavish in adhering to C traditions.

As for why it isn't in Ruby: Matz didn't want it. That's really the ultimate reason.

The reason no such thing exists in Smalltalk is because it's part of the language's overriding philosophy that assigning a variable is fundamentally a different kind of thing than sending a message to an object — it's on a different level. This thinking probably influenced Matz in designing Ruby.

It wouldn't be impossible to include it in Ruby — you could easily write a preprocessor that transforms all ++ into +=1. but evidently Matz didn't like the idea of an operator that did a "hidden assignment." It also seems a little strange to have an operator with a hidden integer operand inside of it. No other operator in the language works that way.

查看更多
登录 后发表回答