[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

to_i() bug?

JZ

7/15/2005 10:04:00 AM

p '1201'.to_i(2)
>>> 1
why result is 1 instead of 0?

p '1201'.to_i(3)
>>> 46
correct

--
JZ
4 Answers

ts

7/15/2005 10:12:00 AM

0

>>>>> "J" == JZ <usenet@zabiello.com> writes:

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





JZ

7/15/2005 10:35:00 AM

0

Dnia Fri, 15 Jul 2005 19:11:43 +0900, ts napisa3(a):

>> why result is 1 instead of 0?
>
> 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.

--
JZ

Paul Brannan

7/15/2005 1:10:00 PM

0

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




JZ

7/15/2005 2:03:00 PM

0

Dnia Fri, 15 Jul 2005 22:10:00 +0900, Paul Brannan napisa3(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... for Ruby? How Ruby is developed?

--
JZ