What causes the error in the following code?
ruby -e "puts 1++" -e:1: syntax error, unexpected $end
or
ruby -e "x=1; puts x++;" -e:1: syntax error, unexpected ';'
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.
To increment a number, simply write x += 1 .
It turns out that the author of Ruby, matz suggests the official way to increment and decrement variables in ruby is by using the += and -= operators.
Ruby doesn't have an ++
operator. You can do puts 1.next
though. Note that for your second example this would not change the value of x
, in that case you'd have to use x += 1
.
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