Knowledge Point:What is to_i?

Published on:

We can see the source code if we refer to the api-dock below:

to_i (String) - APIdock

code
static VALUE
rb_str_to_i(int argc, VALUE *argv, VALUE str)
{
int base;

if (argc == 0) base = 10;
else {
    VALUE b;

    rb_scan_args(argc, argv, "01", &b);
    base = NUM2INT(b);
}
if (base < 0) {
    rb_raise(rb_eArgError, "invalid radix %d", base);
}
return rb_str_to_inum(str, base, FALSE);
}

So it’s clear that it returns the valid number.
If there is not a valid number at the start of str, 0 is returned.

Comments

comments powered by Disqus