p '1201'.to_i(2)
1
why result is 1 instead of 0?
p '1201'.to_i(3)
46
correct
···
--
JZ
p '1201'.to_i(2)
1
why result is 1 instead of 0?
p '1201'.to_i(3)
46
correct
--
JZ
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
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.
Dnia Fri, 15 Jul 2005 19:11:43 +0900, ts napisał(a):
why result is 1 instead of 0?
moulon% ruby -e 'p "1A01".to_i(2); p "10B01".to_i(2)'
1
2
--
JZ
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
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.
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
PEP 0 – Index of Python Enhancement Proposals (PEPs) | peps.python.org for Ruby? How Ruby is developed?
Dnia Fri, 15 Jul 2005 22:10:00 +0900, Paul Brannan napisał(a):
--
JZ