John J. wrote:
If it returned nil, then you’d get exceptions and it would be
pointless to have nil respond to to_i
You got it wrong. I’m not asking for #to_i returning nil.
NilClass#to_i shouldn’t be there in the first place.
Sure, nil.to_i returning nil could also make sense in a way,
Wrong. See above.
Jeremy McAnally wrote:
I expect to get a converted object or some Error (TypeError maybe?)
back from any to_ method. Giving me the same object back or nil
doesn’t make any sense…
You got it wrong too (am I that confusing? :).
As others have noted, I think the current behavior makes sense: I have
nil (whatever…money, cats, etc.) I’d think an integer representation
would be 0.
nil has other uses besides representing nothing: it means false in a
boolean context.
If nil
Under that logic then zero must evaluate to false, just like C and
Python does.
I don’t agree with that, of course.
Chand Perrin wrote:
What would you expect it to return, and why would you think that should
be the expected behavior?
I’d expect the same behavior as FalseClass and TrueClass: undefined
method.
Because if I want 0 would expect or send 0, not nil.to_i.
Because it doesn’t make sense to me that nil, which means false also,
can be represented as zero, when zero doesn’t mean false, but true.
Trans wrote:
If it were not for
that convenience we’d have a bunch of these all over the place:
(x ? x.to_i : 0)
Is that so common? Maybe I haven’t written that many scripts, but I
can’t
remember right now somewhere where I needed that. Ok, maybe parsing
parameters.
NilClass#to_s actually makes some sense in a context where you want to
serialize objects; “” means exactly nothing (in that context!)
Trans wrote:
@want_an_integer = want_an_integer
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.
Maybe it’s a matter of taste, but I validate parameters before calling
methods,
not inside methods. If you feed unexpected parameters to a method, well,
you
should get an exception. Right?
mortee wrote:
Well, if you’d like it so much, why not just redefine it in your own
programs? Everyone else seems to expect it to return 0 instead of being
hostile by throwing an exception…
Oh, c’mon …
Chad P. wrote:
How about any circumstance in which one performs some kind of counting
function in code, and operates on the number of whatever is counted,
where no specific value is yet applied to the variable in question until
the first item is counted?
I don’t think I understood you. Correct me plese, but I think you’re
talking
about an accumulator? In that case, you should start from zero, not nil.