Ruby: How to increment a number that may be nil?
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.
精彩评论