No increment operator (++) in Ruby?

RubyOperators

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkizitView Question on Stackoverflow
Solution 1 - RubyDaveView Answer on Stackoverflow
Solution 2 - RubymikejView Answer on Stackoverflow
Solution 3 - RubyMartin BeanView Answer on Stackoverflow