From: Robert Klemme Date: 2003-11-17T10:25:04+09:00 Subject: Re: to_i "Artur Merke" schrieb im Newsbeitrag news:Pine.LNX.4.33.0311111240420.23480-100000@as0203.cs.uni-dortmund.de... > > IMHO this is a struggle between convenience and cleanness. I guess > > Matz decided for convenience in this case, maybe because in most cases > > using 0 is ok. If you want to do correct input checking you do > > /^[+-]?\d+$/ =~ foo anyway. > > > IMO, it has to do with the principle of least surprise, and it is a BIG > surprise to get > "hello".to_i -> 0 > I think this should be viewed more general (not just for the methods to_i, > to_f etc.). This is clearly dependent on the nature of the expectations, as your posting demonstrates. If you expect to_i to return a number you'd be very surprised to find nil there and see something like this: 14:04:17 [extranet]: ruby -e '1 + nil' -e:1:in `+': nil can't be coerced into Fixnum (TypeError) from -e:1 14:13:25 [extranet]: > If the application of a method makes no sense for an input, > then a nil value makes more sense as a return value (and shouldn't > surprise anybody), then an arbitrary ambiguous value. It might very well be that in most cases using 0 as value is ok. I'm not in a position to estimate the amounts of either sort of situation. I just guess that Matz decided to do it this way. IMHO both solutions can be justified. Moreover, there's a third solution equally reasonable: make to_i throw an exception if the instance at hand cannot be converted into a number. But in a way returning nil or throwing an exception would break the pattern of the to_XYZ methods: they always return something. Even to_a creates an array if the instance at hand is not a collection type at all. If to_a would return nil or throw in those cases you'd always have to do error checking, which you don't have to with the current implementation: def print_all(obj) obj.to_a.each {|e| puts e} end This works with all instances equally well because to_a behaves the way it does. Often there are more reasonable solutions and one has to pick one. In this case it defeats your expectations but maybe it doesn't for many others... Kind regards robert