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 == ......
<< and + are methods (in Ruby, santa << ' Nick' is the same as santa. <<(' Nick') ), while += is a shortcut combining assignment and the concatenation method.
In fact, there is no way to alter a Numeric in place in Ruby. 3 is always three. The only way to “increment a number” is to update the variable to point to a different number. Thus, the implementation of #+= as syntax sugar.
PHP supports C-style pre- and post-increment and decrement operators. Note: The increment/decrement operators only affect numbers and strings. Arrays, objects, booleans and resources are not affected. Decrementing null values has no effect too, but incrementing them results in 1 .
Ruby has no pre/post increment/decrement operator. For instance,
x++
orx--
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 writex += 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):
- ++ and -- are NOT reserved operator in Ruby.
- 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.
- self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With