No increment operator (++) in Ruby?
RubyOperatorsRuby Problem Overview
> Possible Duplicate:
> Why doesn't Ruby support i++ or i— for fixnum?
Why is there no increment operator in Ruby?
e.g.
i++
++i
Is the ++
operator used for something else? Is there a real reason for this?
Ruby Solutions
Solution 1 - Ruby
> Ruby has no pre/post increment/decrement operator. For instance, x++
or x--
will fail to parse. More importantly, ++x
or --x
will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ......
To increment a number, simply write x += 1
.
Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)
That explains it better than I ever could.
EDIT: and the reason from the language author himself (source):
> 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.
Solution 2 - Ruby
From a posting by Matz:
> (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.
Solution 3 - Ruby
I don't think that notation is available because—unlike say PHP or C—everything in Ruby is an object.
Sure you could use $var=0; $var++
in PHP, but that's because it's a variable and not an object. Therefore, $var = new stdClass(); $var++
would probably throw an error.
I'm not a Ruby or RoR programmer, so I'm sure someone can verify the above or rectify it if it's inaccurate.