DEV Community

David Aldridge
David Aldridge

Posted on • Edited on

Avoid converting nil to zero in Ruby with this Quick Tip

Converting values to an Integer, Float or BigDecimal (or even Rational) in Ruby sometimes comes with an unwelcome side effect: that nil responds to #to_i, #to_f, #to_d, or #to_r by returning a class-appropriate zero value.

Sometimes this is fine.

When it isn't, here is a quick tip for avoiding it - use the safe navigation operator, which does not send the method that follows it to nil.

irb(main):001:0> nil.to_i
=> 0
irb(main):002:0> nil&.to_i
=> nil
irb(main):003:0> nil.to_f
=> 0.0
irb(main):004:0> nil&.to_f
=> nil
Enter fullscreen mode Exit fullscreen mode

That's it. Happy navigating!

Top comments (0)