From: Trans Date: 2007-10-15T19:43:29+09:00 Subject: Re: nil.to_i returning zero On Oct 15, 6:27 am, "Robert Dober" wrote: > On 10/15/07, Konrad Meyer wrote: > > > > > Quoth Michael Fellinger: > > > On 10/15/07, Chad Perrin wrote: > > > > On Mon, Oct 15, 2007 at 04:40:35AM +0900, Gerardo Santana G?mez Garrido > > wrote: > > > > > > What does nil.to_i return? Zero. And I wonder why. How can nil be > > > > > interpreted as a number. It's beyond me. > > > > > There's been a few attempts to answer the question already. I'm curious, > > > > though: > > > > > What would you expect it to return, and why would you think that should > > > > be the expected behavior? > > > > > Nothing immediately occurs to me as a better result of evaluating > > > > nil.to_i than 0, within the context of the Ruby language, but if you have > > > > an alternative view I'm open to learning from it. > > > > nil.to_i > > > # > NoMethodError: undefined method `to_i' for nil:NilClass > > > Integer(nil) > > > # > TypeError: can't convert nil into Integer > > > > This is on my wish list for Christmas among other things. > > > Thing is, #to_i explicitly does *not* throw errors -- that's what Integer() is > > for. Current (1.8.6) ruby doesn't error on Integer(nil) either, but IMO it > > should. > > But Michael did not ask NilClass#to_i to throw an error, he did ask it > to go away :) If it goes away you get a NoMethodError. > Now I am completely impartial on the behavior, but if nil.to_i is > confusing for some folks it might be a good idea to put it away unless > other folks really need it. > My pragmatic question is therefore: > nil.to_i usecases anyone? def any_method(want_an_integer=nil) @want_an_integer = want_an_integer.to_i @want_an_integer + 1 # ... whatever ... end It is generally better to use nil for default parameters b/c it reduces the potential for errors and increases the flexability of the design. The same is true of using "to_i". If you did it otherwise: def any_method(want_an_integer=0) @want_an_integer = want_an_integer @want_an_integer + 1 end Errors would occur on calling: any_method(nil) and any_method("0") And to compensate one would have to put the flexability into the call: any_method((some_var || 0).to_i) Which IMO, is much less desirable. T.