DEV Community

Cisco Vlahakis
Cisco Vlahakis

Posted on

Understanding increment syntax in Ruby

In Javascript, we can concisely increment a variable by 1:

x++
Enter fullscreen mode Exit fullscreen mode

Fast, easy, and simple! I tried doing the same thing in Ruby! Alas, that did not work. In Ruby, there is no x++ operator like there is in JS. The reason for this is largely due to the design philosophy of the Ruby language.

Ruby emphasizes readability and and prefers explicit operations over shorthand ones. In Ruby, we do:

x+=1
Enter fullscreen mode Exit fullscreen mode

The x+=1 operation is clear: it increases the value of x by 1. In addition, Ruby has another method to increment a variable:

x = 1
x = x.next
Enter fullscreen mode Exit fullscreen mode

Of course, the good old fashioned

x = x + 1
Enter fullscreen mode Exit fullscreen mode

works just fine, too :)

Although I understand Ruby prefers explicit operations, I do prefer the simplicity of JS and Python. Once you've been coding awhile, you come to appreciate the simpler syntax. However, an explicit language like Ruby is great for beginners understanding the basics. Every language has their pros and cons.

Top comments (0)