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
?
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 == ......
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.
<< and + are methods (in Ruby, santa << ' Nick' is the same as santa. <<(' Nick') ), while += is a shortcut combining assignment and the concatenation method.
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."
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
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