Paul Brannan
7/15/2005 1:10:00 PM
On Fri, Jul 15, 2005 at 07:35:52PM +0900, JZ wrote:
> I found, Ruby assumes that it will extract all characters up to first
> impossible character. Is seems to be wrong assumption. to_i should
> return 0 or exception for all impossible conversions.
Ruby chose the same behavior as the ato* functions strto* in C. I agree
this is not optimal, because it doesn't allow for easy data validation;
because it is so simple to use though, it actually *encourages* writing
code that doesn't do data validation.
C in addition provides to strto* functions, which in addition to
stopping at the first invalid character, also give the user a way to
obtain the position of the first invalid character, which is useful in
parsing. I think most people who need this level of parsing in Ruby
choose a different method of parsing, such as regexes or a parser
generator.
The Integer() and Float() methods are available if you want to validate
your data, but in 1.8.x, Integer() does not take a base as an argument.
These methods raise an exception for invalid data. It is unfortunate
that the interface for these methods is not self-documenting.
Paul