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?
What’s the science behind the fact that the to_i method in Ruby’s NilClass instances
Share
NilClassdefines#to_ifor the same reason it defines a#to_athat returns[].It’s giving you something of the right type but an empty sort of value.This is actually quite useful. For example:
becomes:
Much nicer! (Erb is calling #to_s which, for nil, is “”.) And:
becomes:
The short conversions exist when only a representation is needed. The long conversions are the ones that the Ruby core methods call and they require something very close. Use them if you want a type check.
That is: