Method: Kernel#Integer

Defined in:
object.c

#Integer(arg, base = 0, exception: true) ⇒ Integer?

Converts arg to an Integer. Numeric types are converted directly (with floating point numbers being truncated). base (0, or between 2 and 36) is a base for integer string representation. If arg is a String, when base is omitted or equals zero, radix indicators (0, 0b, and 0x) are honored. In any case, strings should consist only of one or more digits, except for that a sign, one underscore between two digits, and leading/trailing spaces are optional. This behavior is different from that of String#to_i. Non string values will be converted by first trying to_int, then to_i.

Passing nil raises a TypeError, while passing a String that does not conform with numeric representation raises an ArgumentError. This behavior can be altered by passing exception: false, in this case a not convertible value will return nil.

Integer(123.999)    #=> 123
Integer("0x1a")     #=> 26
Integer(Time.new)   #=> 1204973019
Integer("0930", 10) #=> 930
Integer("111", 2)   #=> 7
Integer(" +1_0 ")   #=> 10
Integer(nil)        #=> TypeError: can't convert nil into Integer
Integer("x")        #=> ArgumentError: invalid value for Integer(): "x"

Integer("x", exception: false)        #=> nil

Returns:



3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
# File 'object.c', line 3418

static VALUE
rb_f_integer(int argc, VALUE *argv, VALUE obj)
{
    VALUE arg = Qnil, opts = Qnil;
    int base = 0;

    if (argc > 1) {
        int narg = 1;
        VALUE vbase = rb_check_to_int(argv[1]);
        if (!NIL_P(vbase)) {
            base = NUM2INT(vbase);
            narg = 2;
        }
        if (argc > narg) {
            VALUE hash = rb_check_hash_type(argv[argc-1]);
            if (!NIL_P(hash)) {
                opts = rb_extract_keywords(&hash);
                if (!hash) --argc;
            }
        }
    }
    rb_check_arity(argc, 1, 2);
    arg = argv[0];

    return rb_convert_to_integer(arg, base, opts_exception_p(opts));
}