Increment in Ruby

Find this useful? Support us: Star on GitHub 6
Category: Number | Language: Ruby

In Ruby, you can increment a number in several ways. One way is by using the increment operator +=. Here are some examples:

Example 1: Using += operator

x = 5
x += 1
puts x # Output: 6

Example 2: Using += with a floating-point number

y = 3.5
y += 2.5
puts y # Output: 6.0

Example 3: Incrementing by more than 1 using +=

z = 10
z += 3
puts z # Output: 13

Example 4: Alternatively, you can use the succ method to increment a number

a = 7
a = a.succ
puts a # Output: 8

These are just a few of the ways you can increment a number in Ruby. There are several other methods like next, pred, etc. that can be used depending on your requirements.