Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to increment a number that may be nil?

Tags:

ruby

How could I simplify this in Ruby:

x = (x || 0) + 1

?

like image 533
Misha Moroshko Avatar asked Sep 16 '11 06:09

Misha Moroshko


People also ask

How do you increment numbers in Ruby?

In fact, there is no way to alter a Numeric in place in Ruby. 3 is always three. The only way to “increment a number” is to update the variable to point to a different number. Thus, the implementation of #+= as syntax sugar.

What is nil value in Ruby?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.

Is null nil in Ruby?

Let's start out with “Nil” since it's the most common and easy-to-understand way of representing nothingness in Ruby. In terms of what it means, Nil is exactly the same thing as null in other languages.

Does Ruby return nil by default?

By default methods in Ruby are empty, and an empty method returns, by default, nil.


1 Answers

You can use to_i to convert nil to 0

x = x.to_i + 1

Or you can use succ

x = x.to_i.succ

like image 147
Chandra Patni Avatar answered Oct 22 '22 14:10

Chandra Patni