class Integer - RDoc Documentation (original) (raw)

An Integer object represents an integer value.

You can create an Integer object explicitly with:

You can convert certain objects to Integers with:

An attempt to add a singleton method to an instance of this class causes an exception to be raised.

What’s Here

First, what’s elsewhere. Class Integer:

Here, class Integer provides methods for:

Querying

Comparing

Converting

Other

Constants

GMP_VERSION

The version of loaded GMP.

Public Class Methods

sqrt(numeric) → integer click to toggle source

Returns the integer square root of the non-negative integer n, which is the largest non-negative integer less than or equal to the square root of numeric.

Integer.sqrt(0)
Integer.sqrt(1)
Integer.sqrt(24)
Integer.sqrt(25)
Integer.sqrt(10**400)

If numeric is not an Integer, it is converted to an Integer:

Integer.sqrt(Complex(4, 0))
Integer.sqrt(Rational(4, 1)) Integer.sqrt(4.0)
Integer.sqrt(3.14159)

This method is equivalent to Math.sqrt(numeric).floor, except that the result of the latter code may differ from the true value due to the limited precision of floating point arithmetic.

Integer.sqrt(1046)
Math.sqrt(10
46).floor

Raises an exception if numeric is negative.

static VALUE rb_int_s_isqrt(VALUE self, VALUE num) { unsigned long n, sq; num = rb_to_int(num); if (FIXNUM_P(num)) { if (FIXNUM_NEGATIVE_P(num)) { domain_error("isqrt"); } n = FIX2ULONG(num); sq = rb_ulong_isqrt(n); return LONG2FIX(sq); } else { size_t biglen; if (RBIGNUM_NEGATIVE_P(num)) { domain_error("isqrt"); } biglen = BIGNUM_LEN(num); if (biglen == 0) return INT2FIX(0); #if SIZEOF_BDIGIT <= SIZEOF_LONG /* short-circuit */ if (biglen == 1) { n = BIGNUM_DIGITS(num)[0]; sq = rb_ulong_isqrt(n); return ULONG2NUM(sq); } #endif return rb_big_isqrt(num); } }

try_convert(object) → object, integer, or nil click to toggle source

If object is an Integer object, returns object.

Integer.try_convert(1)

Otherwise if object responds to :to_int, calls object.to_int and returns the result.

Integer.try_convert(1.25)

Returns nil if object does not respond to :to_int

Integer.try_convert([])

Raises an exception unless object.to_int returns an Integer object.

static VALUE int_s_try_convert(VALUE self, VALUE num) { return rb_check_integer_type(num); }

Public Instance Methods

self % other → real_number click to toggle source

Returns self modulo other as a real number.

For integer n and real number r, these expressions are equivalent:

n % r n-r*(n/r).floor n.divmod(r)[1]

See Numeric#divmod.

Examples:

10 % 2
10 % 3
10 % 4

10 % -2
10 % -3
10 % -4

10 % 3.0
10 % Rational(3, 1)

VALUE rb_int_modulo(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_mod(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_modulo(x, y); } return num_modulo(x, y); }

self & other → integer click to toggle source

Bitwise AND; each bit in the result is 1 if both corresponding bits in self and other are 1, 0 otherwise:

"%04b" % (0b0101 & 0b0110)

Raises an exception if other is not an Integer.

Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).

VALUE rb_int_and(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_and(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_and(x, y); } return Qnil; }

self * numeric → numeric_result click to toggle source

Performs multiplication:

4 * 2
4 * -2
-4 * 2
4 * 2.0
4 * Rational(1, 3) 4 * Complex(2, 0)

VALUE rb_int_mul(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_mul(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_mul(x, y); } return rb_num_coerce_bin(x, y, '*'); }

self ** numeric → numeric_result click to toggle source

Raises self to the power of numeric:

2 ** 3
2 ** -3
-2 ** 3
-2 ** -3
2 ** 3.3
2 ** Rational(3, 1) 2 ** Complex(3, 0)

VALUE rb_int_pow(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_pow(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_pow(x, y); } return Qnil; }

self + numeric → numeric_result click to toggle source

Performs addition:

2 + 2
-2 + 2
-2 + -2
2 + 2.0
2 + Rational(2, 1) 2 + Complex(2, 0)

VALUE rb_int_plus(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_plus(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_plus(x, y); } return rb_num_coerce_bin(x, y, '+'); }

self - numeric → numeric_result click to toggle source

Performs subtraction:

4 - 2
-4 - 2
-4 - -2
4 - 2.0
4 - Rational(2, 1) 4 - Complex(2, 0)

VALUE rb_int_minus(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_minus(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_minus(x, y); } return rb_num_coerce_bin(x, y, '-'); }

-int → integer click to toggle source

Returns self, negated.

def -@ Primitive.attr! :leaf Primitive.cexpr! 'rb_int_uminus(self)' end

self / numeric → numeric_result click to toggle source

Performs division; for integer numeric, truncates the result to an integer:

4 / 3 # => 1 4 / -3 # => -2 -4 / 3 # => -2 -4 / -3 # => 1

For other +numeric+, returns non-integer result:

4 / 3.0 # => 1.3333333333333333 4 / Rational(3, 1) # => (4/3) 4 / Complex(3, 0) # => ((4/3)+0i)

VALUE rb_int_div(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_div(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_div(x, y); } return Qnil; }

self < other → true or false click to toggle source

Returns true if the value of self is less than that of other:

1 < 0 # => false 1 < 1 # => false 1 < 2 # => true 1 < 0.5 # => false 1 < Rational(1, 2) # => false

Raises an exception if the comparison cannot be made.

static VALUE int_lt(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_lt(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_lt(x, y); } return Qnil; }

self << count → integer click to toggle source

Returns self with bits shifted count positions to the left, or to the right if count is negative:

n = 0b11110000 "%08b" % (n << 1)
"%08b" % (n << 3)
"%08b" % (n << -1) "%08b" % (n << -3)

Related: Integer#>>.

VALUE rb_int_lshift(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return rb_fix_lshift(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_lshift(x, y); } return Qnil; }

self <= real → true or false click to toggle source

Returns true if the value of self is less than or equal to that of other:

1 <= 0
1 <= 1
1 <= 2
1 <= 0.5
1 <= Rational(1, 2)

Raises an exception if the comparison cannot be made.

static VALUE int_le(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_le(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_le(x, y); } return Qnil; }

self <=> other → -1, 0, +1, or nil click to toggle source

Returns:

Examples:

1 <=> 2
1 <=> 1
1 <=> 0
1 <=> 'foo'

1 <=> 1.0
1 <=> Rational(1, 1) 1 <=> Complex(1, 0)

This method is the basis for comparisons in module Comparable.

VALUE rb_int_cmp(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_cmp(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_cmp(x, y); } else { rb_raise(rb_eNotImpError, "need to define '<=>' in %s", rb_obj_classname(x)); } }

self == other → true or false

Returns true if self is numerically equal to other; false otherwise.

1 == 2
1 == 1.0

Related: Integer#eql? (requires other to be an Integer).

Alias for: ===

=== == other -> true or false click to toggle source

Returns true if self is numerically equal to other; false otherwise.

1 == 2
1 == 1.0

Related: Integer#eql? (requires other to be an Integer).

VALUE rb_int_equal(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_equal(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_eq(x, y); } return Qnil; }

Also aliased as: ==

self > other → true or false click to toggle source

Returns true if the value of self is greater than that of other:

1 > 0 # => true 1 > 1 # => false 1 > 2 # => false 1 > 0.5 # => true 1 > Rational(1, 2) # => true

Raises an exception if the comparison cannot be made.

VALUE rb_int_gt(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_gt(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_gt(x, y); } return Qnil; }

self >= real → true or false click to toggle source

Returns true if the value of self is greater than or equal to that of other:

1 >= 0
1 >= 1
1 >= 2
1 >= 0.5
1 >= Rational(1, 2)

Raises an exception if the comparison cannot be made.

VALUE rb_int_ge(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_ge(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_ge(x, y); } return Qnil; }

self >> count → integer click to toggle source

Returns self with bits shifted count positions to the right, or to the left if count is negative:

n = 0b11110000 "%08b" % (n >> 1)
"%08b" % (n >> 3)
"%08b" % (n >> -1) "%08b" % (n >> -3)

Related: Integer#<<.

VALUE rb_int_rshift(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return rb_fix_rshift(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_rshift(x, y); } return Qnil; }

self[offset] → 0 or 1 click to toggle source

self[offset, size] → integer

self[range] → integer

Returns a slice of bits from self.

With argument offset, returns the bit at the given offset, where offset 0 refers to the least significant bit:

n = 0b10 n[0]
n[1]
n[2]
n[3]

In principle, n[i] is equivalent to (n >> i) & 1. Thus, negative index always returns zero:

255[-1]

With arguments offset and size, returns size bits from self, beginning at offset and including bits of greater significance:

n = 0b111000
"%010b" % n[0, 10] "%010b" % n[4, 10]

With argument range, returns range.size bits from self, beginning at range.begin and including bits of greater significance:

n = 0b111000
"%010b" % n[0..9] "%010b" % n[4..9]

Raises an exception if the slice cannot be constructed.

static VALUE int_aref(int const argc, VALUE * const argv, VALUE const num) { rb_check_arity(argc, 1, 2); if (argc == 2) { return int_aref2(num, argv[0], argv[1]); } return int_aref1(num, argv[0]);

return Qnil;

}

self ^ other → integer click to toggle source

Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits in self and other are different, 0 otherwise:

"%04b" % (0b0101 ^ 0b0110)

Raises an exception if other is not an Integer.

Related: Integer#& (bitwise AND), Integer#| (bitwise OR).

static VALUE int_xor(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_xor(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_xor(x, y); } return Qnil; }

abs → integer click to toggle source

Returns the absolute value of self.

(-12345).abs -12345.abs
12345.abs

def abs Primitive.attr! :leaf Primitive.cexpr! 'rb_int_abs(self)' end

allbits?(mask) → true or false click to toggle source

Returns true if all bits that are set (=1) in mask are also set in self; returns false otherwise.

Example values:

0b1010101 self 0b1010100 mask 0b1010100 self & mask true self.allbits?(mask)

0b1010100 self 0b1010101 mask 0b1010100 self & mask false self.allbits?(mask)

Related: Integer#anybits?, Integer#nobits?.

static VALUE int_allbits_p(VALUE num, VALUE mask) { mask = rb_to_int(mask); return rb_int_equal(rb_int_and(num, mask), mask); }

anybits?(mask) → true or false click to toggle source

Returns true if any bit that is set (=1) in mask is also set in self; returns false otherwise.

Example values:

0b10000010 self 0b11111111 mask 0b10000010 self & mask true self.anybits?(mask)

0b00000000 self 0b11111111 mask 0b00000000 self & mask false self.anybits?(mask)

Related: Integer#allbits?, Integer#nobits?.

static VALUE int_anybits_p(VALUE num, VALUE mask) { mask = rb_to_int(mask); return RBOOL(!int_zero_p(rb_int_and(num, mask))); }

bit_length → integer click to toggle source

Returns the number of bits of the value of self, which is the bit position of the highest-order bit that is different from the sign bit (where the least significant bit has bit position 1). If there is no such bit (zero or minus one), returns zero.

This method returns ceil(log2(self < 0 ? -self : self + 1))>.

(-21000-1).bit_length
(-2
1000).bit_length
(-21000+1).bit_length
(-2
12-1).bit_length
(-212).bit_length
(-2
12+1).bit_length
-0x101.bit_length
-0x100.bit_length
-0xff.bit_length
-2.bit_length
-1.bit_length
0.bit_length
1.bit_length
0xff.bit_length
0x100.bit_length
(212-1).bit_length
(2
12).bit_length
(212+1).bit_length
(2
1000-1).bit_length
(21000).bit_length
(2
1000+1).bit_length

For Integer n, this method can be used to detect overflow in Array#pack:

if n.bit_length < 32 [n].pack('l') else raise 'Overflow' end

def bit_length Primitive.attr! :leaf Primitive.cexpr! 'rb_int_bit_length(self)' end

ceil(ndigits = 0) → integer click to toggle source

Returns an integer that is a “ceiling” value for self, as specified by the given ndigits, which must be an integer-convertible object.

Related: Integer#floor.

static VALUE int_ceil(int argc, VALUE* argv, VALUE num) { int ndigits;

if (!rb_check_arity(argc, 0, 1)) return num;
ndigits = NUM2INT(argv[0]);
if (ndigits >= 0) {
    return num;
}
return rb_int_ceil(num, ndigits);

}

ceildiv(numeric) → integer click to toggle source

Returns the result of division self by numeric. rounded up to the nearest integer.

3.ceildiv(3)
4.ceildiv(3)

4.ceildiv(-3)
-4.ceildiv(3)
-4.ceildiv(-3)

3.ceildiv(1.2)

def ceildiv(other) -div(0 - other) end

chr → string click to toggle source

chr(encoding) → string

Returns a 1-character string containing the character represented by the value of self, according to the given encoding.

65.chr
0.chr
255.chr
string = 255.chr(Encoding::UTF_8) string.encoding

Raises an exception if self is negative.

Related: Integer#ord.

static VALUE int_chr(int argc, VALUE *argv, VALUE num) { char c; unsigned int i; rb_encoding *enc;

if (rb_num_to_uint(num, &i) == 0) {
}
else if (FIXNUM_P(num)) {
    rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
}
else {
    rb_raise(rb_eRangeError, "bignum out of char range");
}

switch (argc) {
  case 0:
    if (0xff < i) {
        enc = rb_default_internal_encoding();
        if (!enc) {
            rb_raise(rb_eRangeError, "%u out of char range", i);
        }
        goto decode;
    }
    c = (char)i;
    if (i < 0x80) {
        return rb_usascii_str_new(&c, 1);
    }
    else {
        return rb_str_new(&c, 1);
    }
  case 1:
    break;
  default:
    rb_error_arity(argc, 0, 1);
}
enc = rb_to_encoding(argv[0]);
if (!enc) enc = rb_ascii8bit_encoding();

decode: return rb_enc_uint_chr(i, enc); }

coerce(numeric) → array click to toggle source

Returns an array with both a numeric and a int represented as Integer objects or Float objects.

This is achieved by converting numeric to an Integer or a Float.

A TypeError is raised if the numeric is not an Integer or a Float type.

(0x3FFFFFFFFFFFFFFF+1).coerce(42)

static VALUE rb_int_coerce(VALUE x, VALUE y) { if (RB_INTEGER_TYPE_P(y)) { return rb_assoc_new(y, x); } else { x = rb_Float(x); y = rb_Float(y); return rb_assoc_new(y, x); } }

denominator → 1 click to toggle source

digits(base = 10) → array_of_integers click to toggle source

Returns an array of integers representing the base-radix digits of self; the first element of the array represents the least significant digit:

12345.digits
12345.digits(7)
12345.digits(100)

Raises an exception if self is negative or base is less than 2.

static VALUE rb_int_digits(int argc, VALUE *argv, VALUE num) { VALUE base_value; long base;

if (rb_num_negative_p(num))
    rb_raise(rb_eMathDomainError, "out of domain");

if (rb_check_arity(argc, 0, 1)) {
    base_value = rb_to_int(argv[0]);
    if (!RB_INTEGER_TYPE_P(base_value))
        rb_raise(rb_eTypeError, "wrong argument type %s (expected Integer)",
                 rb_obj_classname(argv[0]));
    if (RB_BIGNUM_TYPE_P(base_value))
        return rb_int_digits_bigbase(num, base_value);

    base = FIX2LONG(base_value);
    if (base < 0)
        rb_raise(rb_eArgError, "negative radix");
    else if (base < 2)
        rb_raise(rb_eArgError, "invalid radix %ld", base);
}
else
    base = 10;

if (FIXNUM_P(num))
    return rb_fix_digits(num, base);
else if (RB_BIGNUM_TYPE_P(num))
    return rb_int_digits_bigbase(num, LONG2FIX(base));

return Qnil;

}

div(numeric) → integer click to toggle source

Performs integer division; returns the integer result of dividing self by numeric:

4.div(3)
4.div(-3)
-4.div(3)
-4.div(-3)
4.div(3.0)
4.div(Rational(3, 1))

Raises an exception if numeric does not have method div.

VALUE rb_int_idiv(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_idiv(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_idiv(x, y); } return num_div(x, y); }

divmod(other) → array click to toggle source

Returns a 2-element array [q, r], where

q = (self/other).floor
r = self % other

Examples:

11.divmod(4)
11.divmod(-4)
-11.divmod(4)
-11.divmod(-4)

12.divmod(4)
12.divmod(-4)
-12.divmod(4)
-12.divmod(-4)

13.divmod(4.0)
13.divmod(Rational(4, 1))

VALUE rb_int_divmod(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_divmod(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_divmod(x, y); } return Qnil; }

downto(limit) {|i| ... } → self click to toggle source

downto(limit) → enumerator

Calls the given block with each integer value from self down to limit; returns self:

a = [] 10.downto(5) {|i| a << i }
a
a = [] 0.downto(-5) {|i| a << i }
a
4.downto(5) {|i| fail 'Cannot happen' }

With no block given, returns an Enumerator.

static VALUE int_downto(VALUE from, VALUE to) { RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size); if (FIXNUM_P(from) && FIXNUM_P(to)) { long i, end;

    end = FIX2LONG(to);
    for (i=FIX2LONG(from); i >= end; i--) {
        rb_yield(LONG2FIX(i));
    }
}
else {
    VALUE i = from, c;

    while (!(c = rb_funcall(i, '<', 1, to))) {
        rb_yield(i);
        i = rb_funcall(i, '-', 1, INT2FIX(1));
    }
    if (NIL_P(c)) rb_cmperr(i, to);
}
return from;

}

even? → true or false click to toggle source

Returns true if self is an even number, false otherwise.

def even? Primitive.attr! :leaf Primitive.cexpr! 'rb_int_even_p(self)' end

fdiv(numeric) → float click to toggle source

Returns the Float result of dividing self by numeric:

4.fdiv(2)
4.fdiv(-2)
-4.fdiv(2)
4.fdiv(2.0)
4.fdiv(Rational(3, 4))

Raises an exception if numeric cannot be converted to a Float.

VALUE rb_int_fdiv(VALUE x, VALUE y) { if (RB_INTEGER_TYPE_P(x)) { return DBL2NUM(rb_int_fdiv_double(x, y)); } return Qnil; }

floor(ndigits = 0) → integer click to toggle source

Returns an integer that is a “floor” value for self, as specified by the given ndigits, which must be an integer-convertible object.

Related: Integer#ceil.

static VALUE int_floor(int argc, VALUE* argv, VALUE num) { int ndigits;

if (!rb_check_arity(argc, 0, 1)) return num;
ndigits = NUM2INT(argv[0]);
if (ndigits >= 0) {
    return num;
}
return rb_int_floor(num, ndigits);

}

gcd(other_int) → integer click to toggle source

Returns the greatest common divisor of the two integers. The result is always positive. 0.gcd(x) and x.gcd(0) return x.abs.

36.gcd(60)
2.gcd(2)
3.gcd(-7)
((1<<31)-1).gcd((1<<61)-1)

VALUE rb_gcd(VALUE self, VALUE other) { other = nurat_int_value(other); return f_gcd(self, other); }

gcdlcm(other_int) → array click to toggle source

Returns an array with the greatest common divisor and the least common multiple of the two integers, [gcd, lcm].

36.gcdlcm(60)
2.gcdlcm(2)
3.gcdlcm(-7)
((1<<31)-1).gcdlcm((1<<61)-1)

VALUE rb_gcdlcm(VALUE self, VALUE other) { other = nurat_int_value(other); return rb_assoc_new(f_gcd(self, other), f_lcm(self, other)); }

inspect(*args)

Returns a string containing the place-value representation of self in radix base (in 2..36).

12345.to_s
12345.to_s(2)
12345.to_s(8)
12345.to_s(10)
12345.to_s(16)
12345.to_s(36)
78546939656932.to_s(36)

Raises an exception if base is out of range.

integer? → true click to toggle source

Since self is already an Integer, always returns true.

lcm(other_int) → integer click to toggle source

Returns the least common multiple of the two integers. The result is always positive. 0.lcm(x) and x.lcm(0) return zero.

36.lcm(60)
2.lcm(2)
3.lcm(-7)
((1<<31)-1).lcm((1<<61)-1)

VALUE rb_lcm(VALUE self, VALUE other) { other = nurat_int_value(other); return f_lcm(self, other); }

magnitude()

Alias for: abs

modulo(p1)

Returns self modulo other as a real number.

For integer n and real number r, these expressions are equivalent:

n % r n-r*(n/r).floor n.divmod(r)[1]

See Numeric#divmod.

Examples:

10 % 2
10 % 3
10 % 4

10 % -2
10 % -3
10 % -4

10 % 3.0
10 % Rational(3, 1)

Alias for: %

next()

Returns the successor integer of self (equivalent to self + 1):

1.succ
-1.succ

Related: Integer#pred (predecessor value).

nobits?(mask) → true or false click to toggle source

Returns true if no bit that is set (=1) in mask is also set in self; returns false otherwise.

Example values:

0b11110000 self 0b00001111 mask 0b00000000 self & mask true self.nobits?(mask)

0b00000001 self 0b11111111 mask 0b00000001 self & mask false self.nobits?(mask)

Related: Integer#allbits?, Integer#anybits?.

static VALUE int_nobits_p(VALUE num, VALUE mask) { mask = rb_to_int(mask); return RBOOL(int_zero_p(rb_int_and(num, mask))); }

numerator → self click to toggle source

odd? → true or false click to toggle source

Returns true if self is an odd number, false otherwise.

def odd? Primitive.attr! :leaf Primitive.cexpr! 'rb_int_odd_p(self)' end

ord → self click to toggle source

Returns self; intended for compatibility to character literals in Ruby 1.9.

pow(numeric) → numeric click to toggle source

pow(integer, integer) → integer

Returns (modular) exponentiation as:

a.pow(b)
a.pow(b, m)

VALUE rb_int_powm(int const argc, VALUE * const argv, VALUE const num) { rb_check_arity(argc, 1, 2);

if (argc == 1) {
    return rb_int_pow(num, argv[0]);
}
else {
    VALUE const a = num;
    VALUE const b = argv[0];
    VALUE m = argv[1];
    int nega_flg = 0;
    if ( ! RB_INTEGER_TYPE_P(b)) {
        rb_raise(rb_eTypeError, "Integer#pow() 2nd argument not allowed unless a 1st argument is integer");
    }
    if (rb_int_negative_p(b)) {
        rb_raise(rb_eRangeError, "Integer#pow() 1st argument cannot be negative when 2nd argument specified");
    }
    if (!RB_INTEGER_TYPE_P(m)) {
        rb_raise(rb_eTypeError, "Integer#pow() 2nd argument not allowed unless all arguments are integers");
    }

    if (rb_int_negative_p(m)) {
        m = rb_int_uminus(m);
        nega_flg = 1;
    }

    if (FIXNUM_P(m)) {
        long const half_val = (long)HALF_LONG_MSB;
        long const mm = FIX2LONG(m);
        if (!mm) rb_num_zerodiv();
        if (mm == 1) return INT2FIX(0);
        if (mm <= half_val) {
            return int_pow_tmp1(rb_int_modulo(a, m), b, mm, nega_flg);
        }
        else {
            return int_pow_tmp2(rb_int_modulo(a, m), b, mm, nega_flg);
        }
    }
    else {
        if (rb_bigzero_p(m)) rb_num_zerodiv();
        if (bignorm(m) == INT2FIX(1)) return INT2FIX(0);
        return int_pow_tmp3(rb_int_modulo(a, m), b, m, nega_flg);
    }
}
UNREACHABLE_RETURN(Qnil);

}

pred → next_integer click to toggle source

Returns the predecessor of self (equivalent to self - 1):

1.pred
-1.pred

Related: Integer#succ (successor value).

static VALUE rb_int_pred(VALUE num) { if (FIXNUM_P(num)) { long i = FIX2LONG(num) - 1; return LONG2NUM(i); } if (RB_BIGNUM_TYPE_P(num)) { return rb_big_minus(num, INT2FIX(1)); } return num_funcall1(num, '-', INT2FIX(1)); }

rationalize([eps]) → rational click to toggle source

Returns the value as a rational. The optional argument eps is always ignored.

static VALUE integer_rationalize(int argc, VALUE *argv, VALUE self) { rb_check_arity(argc, 0, 1); return integer_to_r(self); }

remainder(other) → real_number click to toggle source

Returns the remainder after dividing self by other.

Examples:

11.remainder(4)
11.remainder(-4)
-11.remainder(4)
-11.remainder(-4)

12.remainder(4)
12.remainder(-4)
-12.remainder(4)
-12.remainder(-4)

13.remainder(4.0)
13.remainder(Rational(4, 1))

static VALUE int_remainder(VALUE x, VALUE y) { if (FIXNUM_P(x)) { if (FIXNUM_P(y)) { VALUE z = fix_mod(x, y); RUBY_ASSERT(FIXNUM_P(z)); if (z != INT2FIX(0) && (SIGNED_VALUE)(x ^ y) < 0) z = fix_minus(z, y); return z; } else if (!RB_BIGNUM_TYPE_P(y)) { return num_remainder(x, y); } x = rb_int2big(FIX2LONG(x)); } else if (!RB_BIGNUM_TYPE_P(x)) { return Qnil; } return rb_big_remainder(x, y); }

round(ndigits= 0, half: :up) → integer click to toggle source

Returns self rounded to the nearest value with a precision of ndigits decimal digits.

When ndigits is negative, the returned value has at least ndigits.abs trailing zeros:

555.round(-1)
555.round(-2)
555.round(-3)
-555.round(-2)
555.round(-4)

Returns self when ndigits is zero or positive.

555.round
555.round(1)
555.round(50)

If keyword argument half is given, and self is equidistant from the two candidate values, the rounding is according to the given half value:

Raises and exception if the value for half is invalid.

Related: Integer#truncate.

static VALUE int_round(int argc, VALUE* argv, VALUE num) { int ndigits; int mode; VALUE nd, opt;

if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
ndigits = NUM2INT(nd);
mode = rb_num_get_rounding_option(opt);
if (ndigits >= 0) {
    return num;
}
return rb_int_round(num, ndigits, mode);

}

size → integer click to toggle source

Returns the number of bytes in the machine representation of self; the value is system-dependent:

1.size
-1.size
2147483647.size
(25610 - 1).size (25620 - 1).size (256**40 - 1).size

def size Primitive.attr! :leaf Primitive.cexpr! 'rb_int_size(self)' end

succ → next_integer click to toggle source

Returns the successor integer of self (equivalent to self + 1):

1.succ
-1.succ

Related: Integer#pred (predecessor value).

VALUE rb_int_succ(VALUE num) { if (FIXNUM_P(num)) { long i = FIX2LONG(num) + 1; return LONG2NUM(i); } if (RB_BIGNUM_TYPE_P(num)) { return rb_big_plus(num, INT2FIX(1)); } return num_funcall1(num, '+', INT2FIX(1)); }

Also aliased as: next

times {|i| ... } → self click to toggle source

times → enumerator

Calls the given block self times with each integer in (0..self-1):

a = [] 5.times {|i| a.push(i) } a

With no block given, returns an Enumerator.

def times Primitive.attr! :inline_block unless defined?(yield) return Primitive.cexpr! 'SIZED_ENUMERATOR(self, 0, 0, int_dotimes_size)' end i = 0 while i < self yield i i = i.succ end self end

to_f → float click to toggle source

Converts self to a Float:

1.to_f
-1.to_f

If the value of self does not fit in a Float, the result is infinity:

(10400).to_f
(-10
400).to_f

static VALUE int_to_f(VALUE num) { double val;

if (FIXNUM_P(num)) {
    val = (double)FIX2LONG(num);
}
else if (RB_BIGNUM_TYPE_P(num)) {
    val = rb_big2dbl(num);
}
else {
    rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
}

return DBL2NUM(val);

}

to_i → self click to toggle source

Returns self (which is already an Integer).

to_int → self click to toggle source

Returns self (which is already an Integer).

to_r → rational click to toggle source

Returns the value as a rational.

1.to_r
(1<<64).to_r

static VALUE integer_to_r(VALUE self) { return rb_rational_new1(self); }

to_s(base = 10) → string click to toggle source

Returns a string containing the place-value representation of self in radix base (in 2..36).

12345.to_s
12345.to_s(2)
12345.to_s(8)
12345.to_s(10)
12345.to_s(16)
12345.to_s(36)
78546939656932.to_s(36)

Raises an exception if base is out of range.

VALUE rb_int_to_s(int argc, VALUE *argv, VALUE x) { int base;

if (rb_check_arity(argc, 0, 1))
    base = NUM2INT(argv[0]);
else
    base = 10;
return rb_int2str(x, base);

}

truncate(ndigits = 0) → integer click to toggle source

Returns self truncated (toward zero) to a precision of ndigits decimal digits.

When ndigits is negative, the returned value has at least ndigits.abs trailing zeros:

555.truncate(-1)
555.truncate(-2)
-555.truncate(-2)

Returns self when ndigits is zero or positive.

555.truncate
555.truncate(50)

Related: Integer#round.

static VALUE int_truncate(int argc, VALUE* argv, VALUE num) { int ndigits;

if (!rb_check_arity(argc, 0, 1)) return num;
ndigits = NUM2INT(argv[0]);
if (ndigits >= 0) {
    return num;
}
return rb_int_truncate(num, ndigits);

}

upto(limit) {|i| ... } → self click to toggle source

upto(limit) → enumerator

Calls the given block with each integer value from self up to limit; returns self:

a = [] 5.upto(10) {|i| a << i }
a
a = [] -5.upto(0) {|i| a << i }
a
5.upto(4) {|i| fail 'Cannot happen' }

With no block given, returns an Enumerator.

static VALUE int_upto(VALUE from, VALUE to) { RETURN_SIZED_ENUMERATOR(from, 1, &to, int_upto_size); if (FIXNUM_P(from) && FIXNUM_P(to)) { long i, end;

    end = FIX2LONG(to);
    for (i = FIX2LONG(from); i <= end; i++) {
        rb_yield(LONG2FIX(i));
    }
}
else {
    VALUE i = from, c;

    while (!(c = rb_funcall(i, '>', 1, to))) {
        rb_yield(i);
        i = rb_funcall(i, '+', 1, INT2FIX(1));
    }
    ensure_cmp(c, i, to);
}
return from;

}

zero? → true or false click to toggle source

Returns true if self has a zero value, false otherwise.

def zero? Primitive.attr! :leaf Primitive.cexpr! 'rb_int_zero_p(self)' end

self | other → integer click to toggle source

Bitwise OR; each bit in the result is 1 if either corresponding bit in self or other is 1, 0 otherwise:

"%04b" % (0b0101 | 0b0110)

Raises an exception if other is not an Integer.

Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).

static VALUE int_or(VALUE x, VALUE y) { if (FIXNUM_P(x)) { return fix_or(x, y); } else if (RB_BIGNUM_TYPE_P(x)) { return rb_big_or(x, y); } return Qnil; }

~int → integer click to toggle source

One’s complement: returns the value of self with each bit inverted.

Because an integer value is conceptually of infinite length, the result acts as if it had an infinite number of one bits to the left. In hex representations, this is displayed as two periods to the left of the digits:

sprintf("%X", ~0x1122334455)

def ~ Primitive.attr! :leaf Primitive.cexpr! 'rb_int_comp(self)' end