Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment variable in ruby [duplicate]

In Java, something like i++ would increment i by 1.

How can I do in Ruby? Surely there has to be a better way than i = i + 1?

like image 329
Carter Shaw Avatar asked Sep 30 '13 15:09

Carter Shaw


People also ask

Can you do i ++ in 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 == ......

How do you increment a variable 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.

What does += mean in Ruby?

<< and + are methods (in Ruby, santa << ' Nick' is the same as santa. <<(' Nick') ), while += is a shortcut combining assignment and the concatenation method.

Does Ruby have double?

Strings primarily exist within either single quotes ( ' ) or double quotes ( " ) in Ruby, so to create a string, enclose a sequence of characters in quotes, like this: "This is a string in double quotes."


1 Answers

From the documentation,

Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse

So, you can do

i += 1 

which is equivalent of i = i + 1

like image 108
karthikr Avatar answered Sep 24 '22 13:09

karthikr