to_i() bug?

T

ts

J> why result is 1 instead of 0?

moulon% ruby -e 'p "1A01".to_i(2); p "10B01".to_i(2)'
1
2
moulon%



Guy Decoux
 
J

JZ

Dnia Fri, 15 Jul 2005 19:11:43 +0900, ts napisa³(a):
moulon% ruby -e 'p "1A01".to_i(2); p "10B01".to_i(2)'
1
2

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.
 
P

Paul Brannan

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
 
J

JZ

Dnia Fri, 15 Jul 2005 22:10:00 +0900, Paul Brannan napisa³(a):
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.

I need the base. I used another way. This is my code I had to prepare:

def bases(n, min=2)
result = []
n.split(//).each do |c|
pos = "0123456789abcdef".index(c)
min = pos+1 if min <= pos
end
min.upto(16) { |base| result << [base, n.to_i(base)] }
return result
end

p bases('10a')

It is unfortunate that the interface for these methods is not
self-documenting.

I really like pythonic docstring idea. Very comfortable and simple way for
adding documentation to classes, methods etc. Is there any equivalent of
http://python.org/peps/ for Ruby? How Ruby is developed?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top