开发者

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

开发者 https://www.devze.com 2023-04-05 19:43 出处:网络
How could I simplify this开发者_JAVA技巧 in Ruby: x = (x || 0) + 1 ?You can use to_i to convert nil to 0

How could I simplify this开发者_JAVA技巧 in Ruby:

x = (x || 0) + 1

?


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


That depends on what you consider simple. You could use

(x ||= 0) += 1

but I think I'd settle for your version.

If x is a Hash value, see this answer for using default values in Hashes.


Your code may end in an error:

x = 'a'
x = (x || 0) + 1 #can't convert Fixnum into String (TypeError)

There is the possibility to use to_i with +1 or succ (see Chandras answer)

But perhaps only succ will help you also:

x = x.succ if x.respond_to?(:succ)

The correct answer depend on your input data and what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号