Basically Integer applies the same semantics as the Ruby parser while #to_i just grabs the first sequence of digits, treats it as a decimal
number and turns it into an int. If there is no such sequence it falls
back to 0.
Kind regards
rober
···
2009/10/13 Brian Candler <b.candler@pobox.com>:
David A. Black wrote:
But it doesn't mind whitespace:
Integer("\t \n 123\n ") => 123
(leading and trailing whitespace that is)
Beware that Integer() as well as being fussier, also implements special
treatment of leading 0 (octal) and 0x (hex).
* Robert Klemme <shortcutter@googlemail.com> (2009-10-13) schrieb:
Basically Integer applies the same semantics as the Ruby parser while #to_i just grabs the first sequence of digits, treats it as a decimal
number and turns it into an int. If there is no such sequence it falls
back to 0.
A little correction: to_i is passed the radix, which by default is 10.
It will return zero if the first character is not the set of digits for
that radix, otherwise it will turn the run of digits at the front of the
string into an integer according to the radix.
* Robert Klemme <shortcutter@googlemail.com> (2009-10-13) schrieb:
Basically Integer applies the same semantics as the Ruby parser while #to_i just grabs the first sequence of digits, treats it as a decimal
number and turns it into an int. If there is no such sequence it falls
back to 0.
A little correction: to_i is passed the radix, which by default is 10.
Thanks for correcting me!
It will return zero if the first character is not the set of digits for
that radix, otherwise it will turn the run of digits at the front of the
string into an integer according to the radix.
You meant to say "the first _non whitespace_ character".
* Robert Klemme <shortcutter@googlemail.com> (2009-10-20) schrieb:
* Robert Klemme <shortcutter@googlemail.com> (2009-10-13) schrieb:
Basically Integer applies the same semantics as the Ruby parser while #to_i just grabs the first sequence of digits, treats it as a decimal
number and turns it into an int. If there is no such sequence it falls
back to 0.
A little correction: to_i is passed the radix, which by default is 10.
Thanks for correcting me!
It will return zero if the first character is not the set of digits for
that radix, otherwise it will turn the run of digits at the front of the
string into an integer according to the radix.
You meant to say "the first _non whitespace_ character".
True. Whitespace at the start of the string seems to be ignored, but is
a stopper everywhere else.
It was complicated enough the way I wrote it. I looked for the ri
documentation on to_i, but all the standard library ri docs seem to be
gone on my computer, strange.
I suppose the code is like this, only better:
def to_i radix=10
s = 0
s += 1 while self[s,1] == "\s"
(s...length).inject(0) | val, i |
d = self[i,1] # wah!
next val if d == '_'
digit = radix_digit(d, radix)
break val if digit < 0
val *= radix
val += digit
end
end