DEV Community

David Aldridge
David Aldridge

Posted on • Edited on

1 2

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)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay