class Integer
An Integer object represents an integer value.
You can create an Integer object explicitly with:
You can convert certain objects to Integers with:
Method
Integer.
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:
Inherits fromclass Numeric andclass Object.
Includesmodule Comparable.
Here, class Integer provides methods for:
Querying¶↑
allbits?: Returns whether all bits inselfare set.anybits?: Returns whether any bits inselfare set.nobits?: Returns whether no bits inselfare set.
Comparing¶↑
<: Returns whetherselfis less than the given value.<=: Returns whetherselfis less than or equal to the given value.<=>: Returns a number indicating whetherselfis less than, equal to, or greater than the given value.==(aliased as===): Returns whetherselfis equal to the givenvalue.
>: Returns whetherselfis greater than the given value.>=: Returns whetherselfis greater than or equal to the given value.
Converting¶↑
::sqrt: Returns the integer square root of the given value.::try_convert: Returns the given value converted to an Integer.&: Returns the bitwise AND ofselfand the given value.*: Returns the product ofselfand the given value.**: Returns the value ofselfraised to the power of the given value.+: Returns the sum ofselfand the given value.-: Returns the difference ofselfand the given value./: Returns the quotient ofselfand the given value.<<: Returns the value ofselfafter a leftward bit-shift.>>: Returns the value ofselfafter a rightward bit-shift.[]: Returns a slice of bits fromself.^: Returns the bitwise EXCLUSIVE OR ofselfand the given value.|: Returns the bitwise OR ofselfand the given value.ceil: Returns the smallest number greater than or equal toself.chr: Returns a 1-character string containing the character represented by the value ofself.digits: Returns an array of integers representing the base-radix digits ofself.div: Returns the integer result of dividingselfby the given value.divmod: Returns a 2-element array containing the quotient and remainder results of dividingselfby the given value.fdiv: Returns theFloatresult of dividingselfby the given value.floor: Returns the greatest number smaller than or equal toself.pow: Returns the modular exponentiation ofself.pred: Returns the integer predecessor ofself.remainder: Returns the remainder after dividingselfby the given value.round: Returnsselfrounded to the nearest value with the given precision.succ(aliased asnext): Returns the integer successor ofself.to_s(aliased asinspect): Returns a string containing the place-value representation ofselfin the given radix.truncate: Returnsselftruncated to the given precision.
Other¶↑
Constants
- GMP_VERSION
The version of loaded GMP.
Public Class Methods
Source
static VALUErb_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); }}Returns the integer square root of the non-negative integern, which is the largest non-negative integer less than or equal to the square root ofnumeric.
Integer.sqrt(0)# => 0Integer.sqrt(1)# => 1Integer.sqrt(24)# => 4Integer.sqrt(25)# => 5Integer.sqrt(10**400)# => 10**200
Ifnumeric is not an Integer, it is converted to an Integer:
Integer.sqrt(Complex(4,0))# => 2Integer.sqrt(Rational(4,1))# => 2Integer.sqrt(4.0)# => 2Integer.sqrt(3.14159)# => 1
This method is equivalent toMath.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(10**46)# => 100000000000000000000000Math.sqrt(10**46).floor# => 99999999999999991611392
Raises an exception ifnumeric is negative.
Source
static VALUEint_s_try_convert(VALUE self, VALUE num){ return rb_check_integer_type(num);}Ifobject is an Integer object, returnsobject.
Integer.try_convert(1)# => 1
Otherwise ifobject responds to:to_int, callsobject.to_int and returns the result.
Integer.try_convert(1.25)# => 1
Returnsnil ifobject does not respond to:to_int
Integer.try_convert([])# => nil
Raises an exception unlessobject.to_int returns an Integer object.
Public Instance Methods
Source
VALUErb_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);}Returnsself moduloother as a real number.
For integern and real numberr, these expressions are equivalent:
n%rn-r*(n/r).floorn.divmod(r)[1]
SeeNumeric#divmod.
Examples:
10%2# => 010%3# => 110%4# => 210%-2# => 010%-3# => -210%-4# => -210%3.0# => 1.010%Rational(3,1)# => (1/1)
Source
VALUErb_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;}Bitwise AND; each bit in the result is 1 if both corresponding bits inself andother are 1, 0 otherwise:
"%04b"% (0b0101&0b0110)# => "0100"
Raises an exception ifother is not an Integer.
Related:Integer#| (bitwise OR),Integer#^ (bitwise EXCLUSIVE OR).
Source
VALUErb_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, '*');}Performs multiplication:
4*2# => 84*-2# => -8-4*2# => -84*2.0# => 8.04*Rational(1,3)# => (4/3)4*Complex(2,0)# => (8+0i)
Source
VALUErb_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;}Raisesself to the power ofnumeric:
2**3# => 82**-3# => (1/8)-2**3# => -8-2**-3# => (-1/8)2**3.3# => 9.8491553067593292**Rational(3,1)# => (8/1)2**Complex(3,0)# => (8+0i)
Source
VALUErb_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, '+');}Performs addition:
2+2# => 4-2+2# => 0-2+-2# => -42+2.0# => 4.02+Rational(2,1)# => (4/1)2+Complex(2,0)# => (4+0i)
Source
VALUErb_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, '-');}Performs subtraction:
4-2# => 2-4-2# => -6-4--2# => -24-2.0# => 2.04-Rational(2,1)# => (2/1)4-Complex(2,0)# => (2+0i)
Source
# File numeric.rb, line 99def-@Primitive.attr!:leafPrimitive.cexpr!'rb_int_uminus(self)'end
Returnsself, negated.
Source
VALUErb_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;}Performs division; for integernumeric, truncates the result to an integer:
4 / 3 # => 1 4 / -3 # => -2 -4 / 3 # => -2 -4 / -3 # => 1For other +numeric+, returns non-integer result: 4 / 3.0 # => 1.3333333333333333 4 / Rational(3, 1) # => (4/3) 4 / Complex(3, 0) # => ((4/3)+0i)
Source
static VALUEint_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;}Returnstrue if the value ofself is less than that ofother:
1 < 0 # => false 1 < 1 # => false 1 < 2 # => true 1 < 0.5 # => false 1 < Rational(1, 2) # => falseRaises an exception if the comparison cannot be made.
Source
VALUErb_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;}Returnsself with bits shiftedcount positions to the left, or to the right ifcount is negative:
n =0b11110000"%08b"% (n<<1)# => "111100000""%08b"% (n<<3)# => "11110000000""%08b"% (n<<-1)# => "01111000""%08b"% (n<<-3)# => "00011110"
Related:Integer#>>.
Source
static VALUEint_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;}Returnstrue if the value ofself is less than or equal to that ofother:
1<=0# => false1<=1# => true1<=2# => true1<=0.5# => false1<=Rational(1,2)# => false
Raises an exception if the comparison cannot be made.
Source
VALUErb_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)); }}Returns:
-1, if
selfis less thanother.0, if
selfis equal toother.1, if
selfis greater thenother.nil, ifselfandotherare incomparable.
Examples:
1<=>2# => -11<=>1# => 01<=>0# => 11<=>'foo'# => nil1<=>1.0# => 01<=>Rational(1,1)# => 01<=>Complex(1,0)# => 0
This method is the basis for comparisons in moduleComparable.
Returnstrue ifself is numerically equal toother;false otherwise.
1==2#=> false1==1.0#=> true
Related:Integer#eql? (requiresother to be an Integer).
Source
VALUErb_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;}Returnstrue if the value ofself is greater than that ofother:
1 > 0 # => true 1 > 1 # => false 1 > 2 # => false 1 > 0.5 # => true 1 > Rational(1, 2) # => trueRaises an exception if the comparison cannot be made.
Source
VALUErb_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;}Returnstrue if the value ofself is greater than or equal to that ofother:
1>=0# => true1>=1# => true1>=2# => false1>=0.5# => true1>=Rational(1,2)# => true
Raises an exception if the comparison cannot be made.
Source
VALUErb_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;}Returnsself with bits shiftedcount positions to the right, or to the left ifcount is negative:
n =0b11110000"%08b"% (n>>1)# => "01111000""%08b"% (n>>3)# => "00011110""%08b"% (n>>-1)# => "111100000""%08b"% (n>>-3)# => "11110000000"
Related:Integer#<<.
Source
static VALUEint_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;}Returns a slice of bits fromself.
With argumentoffset, returns the bit at the given offset, where offset 0 refers to the least significant bit:
n =0b10# => 2n[0]# => 0n[1]# => 1n[2]# => 0n[3]# => 0
In principle,n[i] is equivalent to(n >> i) & 1. Thus, negative index always returns zero:
255[-1]# => 0
With argumentsoffset andsize, returnssize bits fromself, beginning atoffset and including bits of greater significance:
n =0b111000# => 56"%010b"%n[0,10]# => "0000111000""%010b"%n[4,10]# => "0000000011"
With argumentrange, returnsrange.size bits fromself, beginning atrange.begin and including bits of greater significance:
n =0b111000# => 56"%010b"%n[0..9]# => "0000111000""%010b"%n[4..9]# => "0000000011"
Raises an exception if the slice cannot be constructed.
Source
VALUErb_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;}Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits inself andother are different, 0 otherwise:
"%04b"% (0b0101^0b0110)# => "0011"
Raises an exception ifother is not an Integer.
Source
static VALUEint_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;}Bitwise OR; each bit in the result is 1 if either corresponding bit inself orother is 1, 0 otherwise:
"%04b"% (0b0101|0b0110)# => "0111"
Raises an exception ifother is not an Integer.
Related:Integer#& (bitwise AND),Integer#^ (bitwise EXCLUSIVE OR).
Source
# File numeric.rb, line 118def~Primitive.attr!:leafPrimitive.cexpr!'rb_int_comp(self)'end
One’s complement: returns the value ofself 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)# => "..FEEDDCCBBAA"
Source
# File numeric.rb, line 132defabsPrimitive.attr!:leafPrimitive.cexpr!'rb_int_abs(self)'end
Returns the absolute value ofself.
(-12345).abs# => 12345-12345.abs# => 1234512345.abs# => 12345
Source
static VALUEint_allbits_p(VALUE num, VALUE mask){ mask = rb_to_int(mask); return rb_int_equal(rb_int_and(num, mask), mask);}Returnstrue if all bits that are set (=1) inmask are also set inself; returnsfalse otherwise.
Example values:
0b1010101 self0b1010100 mask0b1010100 self & mask true self.allbits?(mask)0b1010100 self0b1010101 mask0b1010100 self & mask false self.allbits?(mask)
Related:Integer#anybits?,Integer#nobits?.
Source
static VALUEint_anybits_p(VALUE num, VALUE mask){ mask = rb_to_int(mask); return RBOOL(!int_zero_p(rb_int_and(num, mask)));}Returnstrue if any bit that is set (=1) inmask is also set inself; returnsfalse otherwise.
Example values:
0b10000010 self0b11111111 mask0b10000010 self & mask true self.anybits?(mask)0b00000000 self0b11111111 mask0b00000000 self & mask false self.anybits?(mask)
Related:Integer#allbits?,Integer#nobits?.
Source
# File numeric.rb, line 179defbit_lengthPrimitive.attr!:leafPrimitive.cexpr!'rb_int_bit_length(self)'end
Returns the number of bits of the value ofself, 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 returnsceil(log2(self < 0 ? -self : self + 1))>.
(-2**1000-1).bit_length# => 1001(-2**1000).bit_length# => 1000(-2**1000+1).bit_length# => 1000(-2**12-1).bit_length# => 13(-2**12).bit_length# => 12(-2**12+1).bit_length# => 12-0x101.bit_length# => 9-0x100.bit_length# => 8-0xff.bit_length# => 8-2.bit_length# => 1-1.bit_length# => 00.bit_length# => 01.bit_length# => 10xff.bit_length# => 80x100.bit_length# => 9(2**12-1).bit_length# => 12(2**12).bit_length# => 13(2**12+1).bit_length# => 13(2**1000-1).bit_length# => 1000(2**1000).bit_length# => 1001(2**1000+1).bit_length# => 1001
For Integern, this method can be used to detect overflow inArray#pack:
ifn.bit_length<32 [n].pack('l')# No overflow.elseraise'Overflow'end
Source
static VALUEint_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);}Returns an integer that is a “ceiling” value forself, as specified by the givenndigits, which must be aninteger-convertible object.
When
selfis zero, returns zero (regardless of the value ofndigits):0.ceil(2)# => 00.ceil(-2)# => 0
When
selfis non-zero andndigitsis non-negative, returnsself:555.ceil# => 555555.ceil(50)# => 555
When
selfis non-zero andndigitsis negative, returns a value based on a computed granularity:The granularity is
10 ** ndigits.abs.The returned value is the smallest multiple of the granularity that is greater than or equal to
self.
Examples with positive
self:ndigits Granularity 1234.ceil(ndigits) -1 10 1240 -2 100 1300 -3 1000 2000 -4 10000 10000 -5 100000 100000 Examples with negative
self:ndigits Granularity -1234.ceil(ndigits) -1 10 -1230 -2 100 -1200 -3 1000 -1000 -4 10000 0 -5 100000 0
Related:Integer#floor.
Source
# File numeric.rb, line 303defceildiv(other)-div(0-other)end
Returns the result of divisionself bynumeric. rounded up to the nearest integer.
3.ceildiv(3)# => 14.ceildiv(3)# => 24.ceildiv(-3)# => -1-4.ceildiv(3)# => -1-4.ceildiv(-3)# => 23.ceildiv(1.2)# => 3
Source
static VALUEint_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);}Returns a 1-character string containing the character represented by the value ofself, according to the givenencoding.
65.chr# => "A"0.chr# => "\x00"255.chr# => "\xFF"string =255.chr(Encoding::UTF_8)string.encoding# => Encoding::UTF_8
Raises an exception ifself is negative.
Related:Integer#ord.
Source
static VALUErb_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); }}Returns an array with both anumeric and aint represented asInteger objects orFloat objects.
This is achieved by convertingnumeric to anInteger or aFloat.
ATypeError is raised if thenumeric is not anInteger or aFloat type.
(0x3FFFFFFFFFFFFFFF+1).coerce(42)#=> [42, 4611686018427387904]
Source
static VALUErb_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;}Returns an array of integers representing thebase-radix digits ofself; the first element of the array represents the least significant digit:
12345.digits# => [5, 4, 3, 2, 1]12345.digits(7)# => [4, 6, 6, 0, 5]12345.digits(100)# => [45, 23, 1]
Raises an exception ifself is negative orbase is less than 2.
Source
VALUErb_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);}Performs integer division; returns the integer result of dividingself bynumeric:
4.div(3)# => 14.div(-3)# => -2-4.div(3)# => -2-4.div(-3)# => 14.div(3.0)# => 14.div(Rational(3,1))# => 1
Raises an exception ifnumeric does not have methoddiv.
Source
VALUErb_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;}Returns a 2-element array[q, r], where
q = (self/other).floor# Quotientr =self%other# Remainder
Examples:
11.divmod(4)# => [2, 3]11.divmod(-4)# => [-3, -1]-11.divmod(4)# => [-3, 1]-11.divmod(-4)# => [2, -3]12.divmod(4)# => [3, 0]12.divmod(-4)# => [-3, 0]-12.divmod(4)# => [-3, 0]-12.divmod(-4)# => [3, 0]13.divmod(4.0)# => [3, 1.0]13.divmod(Rational(4,1))# => [3, (1/1)]
Source
static VALUEint_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;}Calls the given block with each integer value fromself down tolimit; returnsself:
a = []10.downto(5) {|i|a<<i }# => 10a# => [10, 9, 8, 7, 6, 5]a = []0.downto(-5) {|i|a<<i }# => 0a# => [0, -1, -2, -3, -4, -5]4.downto(5) {|i|fail'Cannot happen' }# => 4
With no block given, returns anEnumerator.
Source
# File numeric.rb, line 188defeven?Primitive.attr!:leafPrimitive.cexpr!'rb_int_even_p(self)'end
Returnstrue ifself is an even number,false otherwise.
Source
VALUErb_int_fdiv(VALUE x, VALUE y){ if (RB_INTEGER_TYPE_P(x)) { return DBL2NUM(rb_int_fdiv_double(x, y)); } return Qnil;}Returns theFloat result of dividingself bynumeric:
4.fdiv(2)# => 2.04.fdiv(-2)# => -2.0-4.fdiv(2)# => -2.04.fdiv(2.0)# => 2.04.fdiv(Rational(3,4))# => 5.333333333333333
Raises an exception ifnumeric cannot be converted to aFloat.
Source
static VALUEint_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);}Returns an integer that is a “floor” value forself, as specified by the givenndigits, which must be aninteger-convertible object.
When
selfis zero, returns zero (regardless of the value ofndigits):0.floor(2)# => 00.floor(-2)# => 0
When
selfis non-zero andndigitsis non-negative, returnsself:555.floor# => 555555.floor(50)# => 555
When
selfis non-zero andndigitsis negative, returns a value based on a computed granularity:The granularity is
10 ** ndigits.abs.The returned value is the largest multiple of the granularity that is less than or equal to
self.
Examples with positive
self:ndigits Granularity 1234.floor(ndigits) -1 10 1230 -2 100 1200 -3 1000 1000 -4 10000 0 -5 100000 0 Examples with negative
self:ndigits Granularity -1234.floor(ndigits) -1 10 -1240 -2 100 -1300 -3 1000 -2000 -4 10000 -10000 -5 100000 -100000
Related:Integer#ceil.
Source
VALUErb_gcd(VALUE self, VALUE other){ other = nurat_int_value(other); return f_gcd(self, other);}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)#=> 122.gcd(2)#=> 23.gcd(-7)#=> 1((1<<31)-1).gcd((1<<61)-1)#=> 1
Source
VALUErb_gcdlcm(VALUE self, VALUE other){ other = nurat_int_value(other); return rb_assoc_new(f_gcd(self, other), f_lcm(self, other));}Returns an array with the greatest common divisor and the least common multiple of the two integers, [gcd, lcm].
36.gcdlcm(60)#=> [12, 180]2.gcdlcm(2)#=> [2, 2]3.gcdlcm(-7)#=> [1, 21]((1<<31)-1).gcdlcm((1<<61)-1)#=> [1, 4951760154835678088235319297]
Source
# File numeric.rb, line 197definteger?trueend
Sinceself is already an Integer, always returnstrue.
Source
VALUErb_lcm(VALUE self, VALUE other){ other = nurat_int_value(other); return f_lcm(self, other);}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)#=> 1802.lcm(2)#=> 23.lcm(-7)#=> 21((1<<31)-1).lcm((1<<61)-1)#=> 4951760154835678088235319297
Source
static VALUEint_nobits_p(VALUE num, VALUE mask){ mask = rb_to_int(mask); return RBOOL(int_zero_p(rb_int_and(num, mask)));}Returnstrue if no bit that is set (=1) inmask is also set inself; returnsfalse otherwise.
Example values:
0b11110000 self0b00001111 mask0b00000000 self & mask true self.nobits?(mask)0b00000001 self0b11111111 mask0b00000001 self & mask false self.nobits?(mask)
Related:Integer#allbits?,Integer#anybits?.
Source
# File numeric.rb, line 207defodd?Primitive.attr!:leafPrimitive.cexpr!'rb_int_odd_p(self)'end
Returnstrue ifself is an odd number,false otherwise.
Source
# File numeric.rb, line 217defordselfend
Returnsself; intended for compatibility to character literals in Ruby 1.9.
Source
VALUErb_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);}Returns (modular) exponentiation as:
a.pow(b)#=> same as a**ba.pow(b,m)#=> same as (a**b) % m, but avoids huge temporary values
Source
static VALUErb_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));}Returns the predecessor ofself (equivalent toself - 1):
1.pred#=> 0-1.pred#=> -2
Related:Integer#succ (successor value).
Source
static VALUEinteger_rationalize(int argc, VALUE *argv, VALUE self){ rb_check_arity(argc, 0, 1); return integer_to_r(self);}Returns the value as a rational. The optional argumenteps is always ignored.
Source
static VALUEint_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);}Returns the remainder after dividingself byother.
Examples:
11.remainder(4)# => 311.remainder(-4)# => 3-11.remainder(4)# => -3-11.remainder(-4)# => -312.remainder(4)# => 012.remainder(-4)# => 0-12.remainder(4)# => 0-12.remainder(-4)# => 013.remainder(4.0)# => 1.013.remainder(Rational(4,1))# => (1/1)
Source
static VALUEint_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);}Returnsself rounded to the nearest value with a precision ofndigits decimal digits.
Whenndigits is negative, the returned value has at leastndigits.abs trailing zeros:
555.round(-1)# => 560555.round(-2)# => 600555.round(-3)# => 1000-555.round(-2)# => -600555.round(-4)# => 0
Returnsself whenndigits is zero or positive.
555.round# => 555555.round(1)# => 555555.round(50)# => 555
If keyword argumenthalf is given, andself is equidistant from the two candidate values, the rounding is according to the givenhalf value:
:upornil: round away from zero:25.round(-1,half::up)# => 30(-25).round(-1,half::up)# => -30
:down: round toward zero:25.round(-1,half::down)# => 20(-25).round(-1,half::down)# => -20
:even: round toward the candidate whose last nonzero digit is even:25.round(-1,half::even)# => 2015.round(-1,half::even)# => 20(-25).round(-1,half::even)# => -20
Raises and exception if the value forhalf is invalid.
Related:Integer#truncate.
Source
# File numeric.rb, line 234defsizePrimitive.attr!:leafPrimitive.cexpr!'rb_int_size(self)'end
Returns the number of bytes in the machine representation ofself; the value is system-dependent:
1.size# => 8-1.size# => 82147483647.size# => 8(256**10-1).size# => 10(256**20-1).size# => 20(256**40-1).size# => 40
Source
VALUErb_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));}Returns the successor integer ofself (equivalent toself + 1):
1.succ#=> 2-1.succ#=> 0
Related:Integer#pred (predecessor value).
Source
# File numeric.rb, line 250deftimesPrimitive.attr!:inline_blockunlessdefined?(yield)returnPrimitive.cexpr!'SIZED_ENUMERATOR(self, 0, 0, int_dotimes_size)'endi =0whilei<selfyieldii =i.succendselfend
Calls the given blockself times with each integer in(0..self-1):
a = []5.times {|i|a.push(i) }# => 5a# => [0, 1, 2, 3, 4]
With no block given, returns anEnumerator.
Source
# File ext/openssl/lib/openssl/bn.rb, line 37defto_bnOpenSSL::BN::new(self)end
Casts anInteger as anOpenSSL::BN
See ‘man bn` for more info.
Source
static VALUEint_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);}Convertsself to a Float:
1.to_f# => 1.0-1.to_f# => -1.0
If the value ofself does not fit in aFloat, the result is infinity:
(10**400).to_f# => Infinity(-10**400).to_f# => -Infinity
Source
# File numeric.rb, line 267defto_iselfend
Returnsself (which is already an Integer).
Source
# File numeric.rb, line 275defto_intselfend
Returnsself (which is already an Integer).
Source
static VALUEinteger_to_r(VALUE self){ return rb_rational_new1(self);}Returns the value as a rational.
1.to_r#=> (1/1)(1<<64).to_r#=> (18446744073709551616/1)
Source
VALUErb_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);}Returns a string containing the place-value representation ofself in radixbase (in 2..36).
12345.to_s# => "12345"12345.to_s(2)# => "11000000111001"12345.to_s(8)# => "30071"12345.to_s(10)# => "12345"12345.to_s(16)# => "3039"12345.to_s(36)# => "9ix"78546939656932.to_s(36)# => "rubyrules"
Raises an exception ifbase is out of range.
Source
static VALUEint_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);}Returnsself truncated (toward zero) to a precision ofndigits decimal digits.
Whenndigits is negative, the returned value has at leastndigits.abs trailing zeros:
555.truncate(-1)# => 550555.truncate(-2)# => 500-555.truncate(-2)# => -500
Returnsself whenndigits is zero or positive.
555.truncate# => 555555.truncate(50)# => 555
Related:Integer#round.
Source
static VALUEint_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;}Calls the given block with each integer value fromself up tolimit; returnsself:
a = []5.upto(10) {|i|a<<i }# => 5a# => [5, 6, 7, 8, 9, 10]a = []-5.upto(0) {|i|a<<i }# => -5a# => [-5, -4, -3, -2, -1, 0]5.upto(4) {|i|fail'Cannot happen' }# => 5
With no block given, returns anEnumerator.
Source
# File numeric.rb, line 283defzero?Primitive.attr!:leafPrimitive.cexpr!'rb_int_zero_p(self)'end
Returnstrue ifself has a zero value,false otherwise.