Robert Klemme
11/19/2003 5:26:00 PM
"Artur Merke" <merke@ls1.cs.uni-dortmund.de> schrieb im Newsbeitrag
news:Pine.LNX.4.33.0311191036400.23486-100000@as0203.cs.uni-dortmund.de...
> Hi,
>
> you don't really want to compare ruby with c! BTW, what you have
overlooked
> is the fact, that c doesn't have a nil return value (0 is only a nil value
> in connection with pointers, not integers), so Kernighan & Richie havn't
> had another option then to return 0, but in ruby you have a nil value, and
> I'm pretty sure ;-), K&R would have chosen to return nil in ruby's to_i
> method.
IMHO there are three reasonable ways to deal with the situation that an item
does not correspond to an integer value:
1) return a specific int value - notably 0.
2) retun a specific non int value - notably nil.
3) throw an exception.
I'd say from a theoretical point of view option 3) is the cleanest. The
exception signals that there is no int representation for the specific item
at hand. In this case I'd prefer not to have to_i in such classes and then
we get no such method error. And, we can check beforehand whether the
conversion will succeed. Drawback: code must catch the exception or do the
check or will be terminated for some values.
Option 1) is next best IMHO, because it ensures that all code will continue
to work although in some cases we will see irritating results because 0 is
the neutral element for addition but not for multiplication etc.
Option 2) is worst since it neither ensures that code works (nil is not an
integer, so math will fail) nor can we omit the check of the converted value
like we can do with exceptions:
n = item.to_i
return false if n.nil?
len = n + 5
# ...
# vs.
begin
len = item.to_i + 5
# ...
rescue NoMethodError
return false
end
Note, that math might not be a too good an example because then tyically one
uses 5 + item and lets coercion to the job (i.e. throw an exception if item
can't be coerced).
I guess that Matz decided to go for opt 1) because it is the best from a
pragmatic point of view.
Regards
robert
> Artur
>
>
> On Tue, 18 Nov 2003, Josef 'Jupp' SCHUGT wrote:
> > Hi!
> >
> > * Artur ; 2003-11-17, 14:20 UTC:
> > > IMO, it has to do with the principle of least surprise, and it is a
> > > BIG surprise to get
> > > "hello".to_i -> 0
> >
> > Let me quote Kernighan & Richie, Programming in C (naive
> > implementation of atoi):
> >
> > int atoi(char s[])
> > {
> > int i, n;
> >
> > n = 0;
> > for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
> > n = 10 * n + (s[i] - '0');
> > return n;
> > }
> >
> > Assuming this sample implementation it is not at all surprising that
> > atoi returns 0 if the argument string does not start with a 'digit'.
> > Given Ruby's C heritage it is no surprise that to_i behaves the same
> > as atoi.
> >
> > Josef 'Jupp' Schugt
> > --
> > .-------.
> > message > 100 kB? / | |
> > sender = spammer? / | R.I.P.|
> > text = spam? / ___| |___
> >
> >
>