Ruby Nil and Zero

Viewed 11683

What's the science behind the fact that the to_i method in Ruby's NilClass instances returns zero? Returning nil or raising an exception would not be more logical?

6 Answers

A concise Ruby 2.3+ method for returning nil for nil.to_i instead of 0, is to use the safe navigation operator:

irb(main):001:0> nil.to_i
=> 0
irb(main):002:0> nil&.to_i
=> nil
Related