Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment an integer in Ruby [duplicate]

Tags:

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 ';' 
like image 232
robert Avatar asked Nov 03 '11 11:11

robert


People also ask

How do you increment an integer in Ruby?

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.

How do you increment a value in Ruby?

To increment a number, simply write x += 1 .

How do you decrement in Ruby?

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.


1 Answers

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.

like image 56
Michael Kohl Avatar answered Sep 17 '22 14:09

Michael Kohl