[I was very surprised to see this question isn’t answered in the FAQ. I was about to add it when I realised I probably wouldn’t get the answer quite right, and something this controversial needs a definitive answer. I don’t have the resources *right now* to search it out, so I pose it here to allow for comment before I add it to the FAQ.]
···
===
Q: Why isn’t ‘x++’ or ‘x–’ valid?
A:
Ruby does not define these operators, nor allow them to be defined as methods.
These operations, in other languages, are mostly used on integers. In Ruby,
integers are immutable, so in-place modiciation of integers (as x++ implies) is
not possible.
At best, x++ could be syntax sugar for ‘x = x + 1’, but for whatever reason -
be it a diminished appetite for sugar, or perhaps no intention to mislead - the
creator of Ruby did not include these operators/methods.
Because Ruby has such good support for iterators, there is actually very little
need for explicit increment/decrement operators. The following statements are
the Ruby equivalents of plain ‘for loops’ and array iteration (the most common
use of x++ in other languages):
10.times do action end
array.each do |x| action(x) end
Beware that these are not actually errors in Ruby. They will be parsed
according to their context, so
x++ # incomplete statement (x + +what?)
array[x++] # parse error
++x # +(+x) == x
–x # -(-x) == x
array[++x] # -> array[x]
Enabling warnings (ruby -w) will alert you in a few cases.
===