Why doesn't Ruby support i++ or i-- (increment/decrement operators)? Why doesn't Ruby support i++ or i-- (increment/decrement operators)? ruby ruby

Why doesn't Ruby support i++ or i-- (increment/decrement operators)?


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.


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).


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.