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

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 powered by Disqus