No Increment Operator (++) in Ruby

Increment variable in ruby

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

Is it possible to change the ++ operator in Ruby?

You cannot change it because there is no operator ++ in Ruby to begin with. That's why you get a syntax error.

See Why doesn't Ruby support i++ or i— (increment/decrement operators)?

How to increment an integer in Ruby

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.

Ruby ++ not work?

Ruby doesn't have ++ or -- operators but += and -= accomplish the same thing. Try using the += notation like this:

a = 1
a+= 1
#=> 2

Here is a good reference list of valid ruby operators.

what's wrong with having post-increment within a block

Ruby has no post-increment operator.

Following statement

v++
v

is equivalent to

v + (+v)

Use v += 1 instead. (It's not an post-increment as you may know.)

How do I increment/decrement a character in Ruby for all possible values?

Depending on what the possible values are, you can use String#next:

"\x0".next
# => "\u0001"

Or, to update an existing value:

c = "\x0"
c.next!

This may well not be what you want:

"z".next
# => "aa"

The simplest way I can think of to increment a character's underlying codepoint is this:

c = 'z'
c = c.ord.next.chr
# => "{"

Decrementing is slightly more complicated:

c = (c.ord - 1).chr
# => "z"

In both cases there's the assumption that you won't step outside of 0..255; you may need to add checks for that.



Related Topics



Leave a reply



Submit