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?
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 ofi++
in your example would actually be 1, not 2 (the new value ofi
would be 2, however).Couldn't this be achieved by adding a new method to the fixnum or Integer class?
returns 2
"Destructive" methods seem to be appended with
!
to warn possible users, so adding a new method callednext!
would pretty much do what was requested ie.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.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.