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?
And in the words of David Black from his book "The Well-Grounded Rubyist":
I think there's another reason:
++
in Ruby wouldn't be remotely useful as in C and its direct successors.The reason being, the
for
keyword: while it's essential in C, it's mostly superfluous in Ruby. Most of the iteration in Ruby is done through Enumerable methods, such aseach
andmap
when iterating through some data structure, andFixnum#times
method, when you need to loop an exact number of times.Actually, as far as I have seen, most of the time
+=1
is used by people freshly migrated to Ruby from C-style languages.In short, it's really questionable if methods
++
and--
would be used at all.I think Matz' reasoning for not liking them is that it actually replaces the variable with a new one.
ex:
Now if somebody could convince him that it should just call #succ! or what not, that would make more sense, and avoid the problem. You can suggest it on ruby core.
Here is how Matz(Yukihiro Matsumoto) explains it in an old thread:
You can define a
.+
self-increment operator:More information on "class Variable" is available in "Class Variable to increment Fixnum objects".
Check these operators from the C-family in Ruby's irb and test them for yourself: