[ruby-talk:01003] Re: a question about to_i
From:
Friedrich Dominicus <Friedrich.Dominicus@...>
Date:
1999-12-20 06:11:50 UTC
List:
ruby-talk #1003
Yukihiro Matsumoto wrote: > > Hi, > > In message "[ruby-talk:00989] a question about to_i" > on 99/12/19, Friedrich Dominicus <Friedrich.Dominicus@inka.de> writes: > > |Sorry, I'm quite new to ruby. But I encounterd the following problem. If > |I have a string "bla" and apply to_i to it I get 0. This seems to be > |quite strange because it is what it is a string so shouldn't an > |exeception be rissen or s.th simular. > > As Gotoken stated in [ruby-talk:00992], String#to_i (i.e. the to_i > method of the String class) always return a integer. This is > inherited from UNIX's atoi() behavior. But at least AFAIK there are some checker routines available in ctype.h things like isdigit, isascii, isalpha. I don't found s.th simular in Ruby libs( sorry if I had overseen some points) > > I can prepare exception raising version of the conversion method, but > we have to decide following: > > * the name of the method > > what is the proper name for the exception raising integer > conversion method of a string. I'm too new to ruby to give some good advice on it. But because my program was "translated" from Python and/or from Scheme and/or from a small Shell-Skript one might thing that the name for the Python exception might be a choice. Here's the python source def sum_to(add_to,val_to_add): old_val = add_to try: add_to = add_to + int(val_to_add) assert add_to == old_val + int(val_to_add), "Adding failed" except ValueError: pass return add_to As mentioned before I'm to new to Ruby to know if that might work in Ruby too. > > * proper behavior > > on what situation, what kind of exception should be raised? > in addition, some may want to retrieve non numeric trailer, > the other may want to specify radix. If there is no number it should fail. If there is a number one might argue that this part should be turned into an int. > > Let's discuss about it. What about tests can_be_integer, can_be_float or the like? If one than would have foo = "123" and call can_be_integer(foo) It'll return true than I'm quite safe callint to_i The question is: Is it worth raising an exception on things that can happen on normal execution? I'm most of my time an Eiffel Programmer but I would not use Exceptions on things that I know can fail and this conversion routines can be applied in many cases so IMO it might be the better behavior here. But it's a difficult field IMO. Let's try the divison by zero. It's easy and cheap to check before but does many check before really appliying a division? And if it's a expensive operation to check if the input it valid than raising an exception might be a better idea. So I don't know what should be the right behavior here. Regards Friedrich