Class: Integer

Inherits:
Numeric show all
Defined in:
numeric.c,
numeric.c

Overview

******************************************************************

An \Integer object represents an integer value.

You can create an \Integer object explicitly with:

- An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].

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 from
  {class Numeric}[rdoc-ref:Numeric@What-27s+Here]
  and {class Object}[rdoc-ref:Object@What-27s+Here].
- Includes {module Comparable}[rdoc-ref:Comparable@What-27s+Here].

Here, class \Integer provides methods for:

- {Querying}[rdoc-ref:Integer@Querying]
- {Comparing}[rdoc-ref:Integer@Comparing]
- {Converting}[rdoc-ref:Integer@Converting]
- {Other}[rdoc-ref:Integer@Other]

=== Querying

- #allbits?: Returns whether all bits in +self+ are set.
- #anybits?: Returns whether any bits in +self+ are set.
- #nobits?: Returns whether no bits in +self+ are set.

=== Comparing

- #<: Returns whether +self+ is less than the given value.
- #<=: Returns whether +self+ is less than or equal to the given value.
- #<=>: Returns a number indicating whether +self+ is less than, equal
  to, or greater than the given value.
- #== (aliased as #===): Returns whether +self+ is equal to the given
                          value.
- #>: Returns whether +self+ is greater than the given value.
- #>=: Returns whether +self+ is 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.
- #% (aliased as #modulo): Returns +self+ modulo the given value.
- #&: Returns the bitwise AND of +self+ and the given value.
- #*: Returns the product of +self+ and the given value.
- #**: Returns the value of +self+ raised to the power of the given value.
- #+: Returns the sum of +self+ and the given value.
- #-: Returns the difference of +self+ and the given value.
- #/: Returns the quotient of +self+ and the given value.
- #<<: Returns the value of +self+ after a leftward bit-shift.
- #>>: Returns the value of +self+ after a rightward bit-shift.
- #[]: Returns a slice of bits from +self+.
- #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
- #|: Returns the bitwise OR of +self+ and the given value.
- #ceil: Returns the smallest number greater than or equal to +self+.
- #chr: Returns a 1-character string containing the character
  represented by the value of +self+.
- #digits: Returns an array of integers representing the base-radix digits
  of +self+.
- #div: Returns the integer result of dividing +self+ by the given value.
- #divmod: Returns a 2-element array containing the quotient and remainder
  results of dividing +self+ by the given value.
- #fdiv: Returns the Float result of dividing +self+ by the given value.
- #floor: Returns the greatest number smaller than or equal to +self+.
- #pow: Returns the modular exponentiation of +self+.
- #pred: Returns the integer predecessor of +self+.
- #remainder: Returns the remainder after dividing +self+ by the given value.
- #round: Returns +self+ rounded to the nearest value with the given precision.
- #succ (aliased as #next): Returns the integer successor of +self+.
- #to_f: Returns +self+ converted to a Float.
- #to_s (aliased as #inspect): Returns a string containing the place-value
  representation of +self+ in the given radix.
- #truncate: Returns +self+ truncated to the given precision.

=== Other

- #downto: Calls the given block with each integer value from +self+
  down to the given value.
- #times: Calls the given block +self+ times with each integer
  in <tt>(0..self-1)</tt>.
- #upto: Calls the given block with each integer value from +self+
  up to the given value.

Constant Summary collapse

GMP_VERSION =

The version of loaded GMP.

rb_sprintf("GMP %s", gmp_version)

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Numeric

#-@, #abs, #abs2, #angle, #arg, #clone, #denominator, #eql?, #i, #magnitude, #negative?, #nonzero?, #numerator, #phase, #polar, #positive?, #quo, #rect, #rectangular, #singleton_method_added, #step, #to_c, #to_int, #zero?

Methods included from Comparable

#between?, #clamp

Class Method Details

.sqrtObject

.try_convert(object) ⇒ Object, ...

If object is an Integer object, returns object.

Integer.try_convert(1) # => 1

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

Integer.try_convert(1.25) # => 1

Returns nil if object does not respond to :to_int

Integer.try_convert([]) # => nil

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

Returns:



6090
6091
6092
6093
6094
# File 'numeric.c', line 6090

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

Instance Method Details

#%(other) ⇒ Object

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              # => 0
10 % 3              # => 1
10 % 4              # => 2

10 % -2             # => 0
10 % -3             # => -2
10 % -4             # => -2

10 % 3.0            # => 1.0
10 % Rational(3, 1) # => (1/1)


4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
# File 'numeric.c', line 4378

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);
}

#&(other) ⇒ Integer

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

"%04b" % (0b0101 & 0b0110) # => "0100"

Raises an exception if other is not an Integer.

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

Returns:



5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
# File 'numeric.c', line 5034

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;
}

#*(numeric) ⇒ Object

Performs multiplication:

4 * 2              # => 8
4 * -2             # => -8
-4 * 2             # => -8
4 * 2.0            # => 8.0
4 * Rational(1, 3) # => (4/3)
4 * Complex(2, 0)  # => (8+0i)


4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
# File 'numeric.c', line 4146

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, '*');
}

#**(numeric) ⇒ Object

Raises self to the power of numeric:

2 ** 3              # => 8
2 ** -3             # => (1/8)
-2 ** 3             # => -8
-2 ** -3            # => (-1/8)
2 ** 3.3            # => 9.849155306759329
2 ** Rational(3, 1) # => (8/1)
2 ** Complex(3, 0)  # => (8+0i)


4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
# File 'numeric.c', line 4639

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;
}

#+(numeric) ⇒ Object

Performs addition:

2 + 2              # => 4
-2 + 2             # => 0
-2 + -2            # => -4
2 + 2.0            # => 4.0
2 + Rational(2, 1) # => (4/1)
2 + Complex(2, 0)  # => (4+0i)


4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
# File 'numeric.c', line 4046

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, '+');
}

#-(numeric) ⇒ Object

Performs subtraction:

4 - 2              # => 2
-4 - 2             # => -6
-4 - -2            # => -2
4 - 2.0            # => 2.0
4 - Rational(2, 1) # => (2/1)
4 - Complex(2, 0)  # => (2+0i)


4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
# File 'numeric.c', line 4091

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, '-');
}

#/(numeric) ⇒ Object

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)


4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
# File 'numeric.c', line 4283

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;
}

#<(other) ⇒ Boolean

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.

Returns:

  • (Boolean)


4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
# File 'numeric.c', line 4898

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;
}

#<<(count) ⇒ Integer

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

n = 0b11110000
"%08b" % (n << 1)  # => "111100000"
"%08b" % (n << 3)  # => "11110000000"
"%08b" % (n << -1) # => "01111000"
"%08b" % (n << -3) # => "00011110"

Related: Integer#>>.

Returns:



5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
# File 'numeric.c', line 5173

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;
}

#<=(real) ⇒ Boolean

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

that of +other+:

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

Raises an exception if the comparison cannot be made.

Returns:

  • (Boolean)


4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
# File 'numeric.c', line 4945

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;
}

#<=>(other) ⇒ -1, ...

Returns:

  • -1, if self is less than other.

  • 0, if self is equal to other.

  • 1, if self is greater then other.

  • nil, if self and other are incomparable.

Examples:

1 <=> 2              # => -1
1 <=> 1              # => 0
1 <=> 0              # => 1
1 <=> 'foo'          # => nil

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

This method is the basis for comparisons in module Comparable.

Returns:

  • (-1, 0, +1, nil)


4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
# File 'numeric.c', line 4759

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));
    }
}

#==(other) ⇒ Boolean

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

1 == 2     #=> false
1 == 1.0   #=> true

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

Returns:

  • (Boolean)


4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
# File 'numeric.c', line 4697

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;
}

#==(other) ⇒ Boolean

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

1 == 2     #=> false
1 == 1.0   #=> true

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

Returns:

  • (Boolean)


4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
# File 'numeric.c', line 4697

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;
}

#>(other) ⇒ Boolean

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.

Returns:

  • (Boolean)


4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
# File 'numeric.c', line 4806

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;
}

#>=(real) ⇒ Boolean

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

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

Raises an exception if the comparison cannot be made.

Returns:

  • (Boolean)


4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
# File 'numeric.c', line 4853

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;
}

#>>(count) ⇒ Integer

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

n = 0b11110000
"%08b" % (n >> 1)  # => "01111000"
"%08b" % (n >> 3)  # => "00011110"
"%08b" % (n >> -1) # => "111100000"
"%08b" % (n >> -3) # => "11110000000"

Related: Integer#<<.

Returns:



5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
# File 'numeric.c', line 5229

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;
}

#[](offset) ⇒ 0, 1 #[](offset, size) ⇒ Integer #[](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 # => 2
n[0]     # => 0
n[1]     # => 1
n[2]     # => 0
n[3]     # => 0

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

255[-1] # => 0

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

n = 0b111000       # => 56
"%010b" % n[0, 10] # => "0000111000"
"%010b" % n[4, 10] # => "0000000011"

With argument range, returns range.size bits from self, beginning at range.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.

Overloads:



5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
# File 'numeric.c', line 5390

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;
}

#^(other) ⇒ Integer

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) # => "0011"

Raises an exception if other is not an Integer.

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

Returns:



5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
# File 'numeric.c', line 5118

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;
}

#allbits?(mask) ⇒ Boolean

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?.

Returns:

  • (Boolean)


3680
3681
3682
3683
3684
3685
# File 'numeric.c', line 3680

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) ⇒ Boolean

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?.

Returns:

  • (Boolean)


3710
3711
3712
3713
3714
3715
# File 'numeric.c', line 3710

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

#ceil(*args) ⇒ Object

:markup: markdown

call-seq:

ceil(ndigits = 0) -> integer

Returns an integer that is a “ceiling” value for ‘self`, as specified by the given `ndigits`, which must be an [integer-convertible object](implicit_conversion.rdoc@Integer-Convertible+Objects).

  • When ‘self` is zero, returns zero (regardless of the value of `ndigits`):

    ```
    0.ceil(2)  # => 0
    0.ceil(-2) # => 0
    ```
    
  • When ‘self` is non-zero and `ndigits` is non-negative, returns `self`:

    ```
    555.ceil     # => 555
    555.ceil(50) # => 555
    ```
    
  • When ‘self` is non-zero and `ndigits` is 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.



5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
# File 'numeric.c', line 5920

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);
}

#chrString #chr(encoding) ⇒ String

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

65.chr                   # => "A"
0.chr                    # => "\x00"
255.chr                  # => "\xFF"
string = 255.chr(Encoding::UTF_8)
string.encoding          # => Encoding::UTF_8

Raises an exception if self is negative.

Related: Integer#ord.

Overloads:



3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
# File 'numeric.c', line 3843

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

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)   #=> [42, 4611686018427387904]

Returns:



6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
# File 'bignum.c', line 6784

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);
    }
}

#digits(base = 10) ⇒ Object

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      # => [5, 4, 3, 2, 1]
12345.digits(7)   # => [4, 6, 6, 0, 5]
12345.digits(100) # => [45, 23, 1]

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



5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
# File 'numeric.c', line 5591

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

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

4.div(3)              # => 1
4.div(-3)             # => -2
-4.div(3)             # => -2
-4.div(-3)            # => 1
4.div(3.0)            # => 1
4.div(Rational(3, 1)) # => 1

Raises an exception if numeric does not have method div.

Returns:



4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
# File 'numeric.c', line 4319

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

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

q = (self/other).floor    # Quotient
r = 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)]

Returns:



4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
# File 'numeric.c', line 4489

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 #downto(limit) ⇒ Object

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

a = []
10.downto(5) {|i| a << i }              # => 10
a                                       # => [10, 9, 8, 7, 6, 5]
a = []
0.downto(-5) {|i| a << i }              # => 0
a                                       # => [0, -1, -2, -3, -4, -5]
4.downto(5) {|i| fail 'Cannot happen' } # => 4

With no block given, returns an Enumerator.

Overloads:

  • #downto(limit) {|i| ... } ⇒ self

    Yields:

    • (i)

    Returns:

    • (self)


5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
# File 'numeric.c', line 5701

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;
}

#fdiv(numeric) ⇒ Float

Returns the Float result of dividing self by numeric:

4.fdiv(2)      # => 2.0
4.fdiv(-2)      # => -2.0
-4.fdiv(2)      # => -2.0
4.fdiv(2.0)      # => 2.0
4.fdiv(Rational(3, 4))      # => 5.333333333333333

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

Returns:



4218
4219
4220
4221
4222
4223
4224
4225
# File 'numeric.c', line 4218

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(*args) ⇒ Object

:markup: markdown

call-seq:

floor(ndigits = 0) -> integer

Returns an integer that is a “floor” value for ‘self`, as specified by the given `ndigits`, which must be an [integer-convertible object](implicit_conversion.rdoc@Integer-Convertible+Objects).

  • When ‘self` is zero, returns zero (regardless of the value of `ndigits`):

    ```
    0.floor(2)  # => 0
    0.floor(-2) # => 0
    ```
    
  • When ‘self` is non-zero and `ndigits` is non-negative, returns `self`:

    ```
    555.floor     # => 555
    555.floor(50) # => 555
    ```
    
  • When ‘self` is non-zero and `ndigits` is 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.



5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
# File 'numeric.c', line 5852

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

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)                  #=> 12
2.gcd(2)                    #=> 2
3.gcd(-7)                   #=> 1
((1<<31)-1).gcd((1<<61)-1)  #=> 1

Returns:



1914
1915
1916
1917
1918
1919
# File 'rational.c', line 1914

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

#gcdlcm(other_int) ⇒ Array

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]

Returns:



1952
1953
1954
1955
1956
1957
# File 'rational.c', line 1952

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

#lcm(other_int) ⇒ Integer

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)                  #=> 180
2.lcm(2)                    #=> 2
3.lcm(-7)                   #=> 21
((1<<31)-1).lcm((1<<61)-1)  #=> 4951760154835678088235319297

Returns:



1933
1934
1935
1936
1937
1938
# File 'rational.c', line 1933

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

#%(other) ⇒ Object

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              # => 0
10 % 3              # => 1
10 % 4              # => 2

10 % -2             # => 0
10 % -3             # => -2
10 % -4             # => -2

10 % 3.0            # => 1.0
10 % Rational(3, 1) # => (1/1)


4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
# File 'numeric.c', line 4378

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);
}

#nextObject

#nobits?(mask) ⇒ Boolean

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?.

Returns:

  • (Boolean)


3740
3741
3742
3743
3744
3745
# File 'numeric.c', line 3740

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

#pow(numeric) ⇒ Numeric #pow(integer, integer) ⇒ Integer

Returns (modular) exponentiation as:

a.pow(b)     #=> same as a**b
a.pow(b, m)  #=> same as (a**b) % m, but avoids huge temporary values

Overloads:



7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
# File 'bignum.c', line 7083

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);
}

#predObject

#rationalize([eps]) ⇒ Object

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



2165
2166
2167
2168
2169
2170
# File 'rational.c', line 2165

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

#remainder(other) ⇒ Object

Returns the remainder after dividing self by other.

Examples:

11.remainder(4)              # => 3
11.remainder(-4)             # => 3
-11.remainder(4)             # => -3
-11.remainder(-4)            # => -3

12.remainder(4)              # => 0
12.remainder(-4)             # => 0
-12.remainder(4)             # => 0
-12.remainder(-4)            # => 0

13.remainder(4.0)            # => 1.0
13.remainder(Rational(4, 1)) # => (1/1)


4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
# File 'numeric.c', line 4413

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

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)      # => 560
555.round(-2)      # => 600
555.round(-3)      # => 1000
-555.round(-2)     # => -600
555.round(-4)      # => 0

Returns self when ndigits is zero or positive.

555.round     # => 555
555.round(1)  # => 555
555.round(50) # => 555

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

  • :up or nil: 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)    # => 20
    15.round(-1, half: :even)    # => 20
    (-25).round(-1, half: :even) # => -20
    

Raises and exception if the value for half is invalid.

Related: Integer#truncate.

Returns:



5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
# File 'numeric.c', line 5780

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);
}

#succObject

#to_fFloat

Converts self to a Float:

1.to_f  # => 1.0
-1.to_f # => -1.0

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

(10**400).to_f  # => Infinity
(-10**400).to_f # => -Infinity

Returns:



5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
# File 'numeric.c', line 5419

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_rObject

Returns the value as a rational.

1.to_r        #=> (1/1)
(1<<64).to_r  #=> (18446744073709551616/1)


2152
2153
2154
2155
2156
# File 'rational.c', line 2152

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

#to_s(base = 10) ⇒ String Also known as: inspect

Returns a string containing the place-value representation of self in radix base (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 if base is out of range.

Returns:



3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
# File 'numeric.c', line 3980

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

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)  # => 550
555.truncate(-2)  # => 500
-555.truncate(-2) # => -500

Returns self when ndigits is zero or positive.

555.truncate     # => 555
555.truncate(50) # => 555

Related: Integer#round.

Returns:



5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
# File 'numeric.c', line 5956

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 #upto(limit) ⇒ Object

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

a = []
5.upto(10) {|i| a << i }              # => 5
a                                     # => [5, 6, 7, 8, 9, 10]
a = []
-5.upto(0) {|i| a << i }              # => -5
a                                     # => [-5, -4, -3, -2, -1, 0]
5.upto(4) {|i| fail 'Cannot happen' } # => 5

With no block given, returns an Enumerator.

Overloads:

  • #upto(limit) {|i| ... } ⇒ self

    Yields:

    • (i)

    Returns:

    • (self)


5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
# File 'numeric.c', line 5651

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;
}

#|(other) ⇒ Integer

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

"%04b" % (0b0101 | 0b0110) # => "0111"

Raises an exception if other is not an Integer.

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

Returns:



5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
# File 'numeric.c', line 5076

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;
}