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
Difference or Value of These Block Coding Styles in Ruby
Get the Name of the Currently Executing Method
How to Implement Enums in Ruby
Error to Install Nokogiri on Osx 10.9 Maverick
How to Get the Match Data For All Occurrences of a Ruby Regular Expression in a String
How to 'Validate' on Destroy in Rails
Why Is This Rmagick Call Generating a Segmentation Fault
Error: Failed to Build Gem Native Extension on Mavericks
Cannot Load Such File - Zlib Even After Using Rvm Pkg Install Zlib
What Does the (Unary) * Operator Do in This Ruby Code
How to Get Source Code of a Method Dynamically and Also Which File Is This Method Locate In
What Are the Ruby Gotchas a Newbie Should Be Warned About
How to Create an Average from a Ruby Array