class Numeric
Numeric is the class from which all higher-level numeric classes should inherit.
Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as Integer are implemented as immediates, which means that each Integer is a single immutable object which is always passed by value.
a = 1 1.object_id == a.object_id #=> true
There can only ever be one instance of the integer 1, for example. Ruby ensures this by preventing instantiation. If duplication is attempted, the same instance is returned.
Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class 1.dup #=> 1 1.object_id == 1.dup.object_id #=> true
For this reason, Numeric should be used when defining other numeric classes.
Classes which inherit from Numeric must implement coerce, which returns a two-member Array containing an object that has been coerced into an instance of the new class and self (see coerce).
Inheriting classes should also implement arithmetic operator methods (+, -, * and /) and the <=> operator (see Comparable). These methods may rely on coerce to ensure interoperability with instances of other numeric classes.
class Tally < Numeric def initialize(string) @string = string end def to_s @string end def to_i @string.size end def coerce(other) [self.class.new('|' * other.to_i), self] end def <=>(other) to_i <=> other.to_i end def +(other) self.class.new('|' * (to_i + other.to_i)) end def -(other) self.class.new('|' * (to_i - other.to_i)) end def *(other) self.class.new('|' * (to_i * other.to_i)) end def /(other) self.class.new('|' * (to_i / other.to_i)) end end tally = Tally.new('||') puts tally * 2 #=> "||||" puts tally > 1 #=> true
What’s Here
First, what’s elsewhere. Class Numeric:
-
Inherits from class Object.
-
Includes module Comparable.
Here, class Numeric provides methods for:
Querying
-
finite?: Returns true unlessselfis infinite or not a number. -
infinite?: Returns -1,nilor +1, depending on whetherselfis-Infinity<tt>, finite, or <tt>+Infinity. -
integer?: Returns whetherselfis an integer. -
negative?: Returns whetherselfis negative. -
nonzero?: Returns whetherselfis not zero. -
positive?: Returns whetherselfis positive. -
real?: Returns whetherselfis a real value. -
zero?: Returns whetherselfis zero.
Comparing
-
<=>: Returns:-
-1 if
selfis less than the given value. -
0 if
selfis equal to the given value. -
1 if
selfis greater than the given value. -
nilifselfand the given value are not comparable.
-
-
eql?: Returns whetherselfand the given value have the same value and type.
Converting
-
%(aliased asmodulo): Returns the remainder ofselfdivided by the given value. -
-@: Returns the value ofself, negated. -
abs(aliased asmagnitude): Returns the absolute value ofself. -
abs2: Returns the square ofself. -
angle(aliased asargandphase): Returns 0 ifselfis positive,Math::PIotherwise. -
ceil: Returns the smallest number greater than or equal toself, to a given precision. -
coerce: Returns array[coerced_self, coerced_other]for the given other value. -
conj(aliased asconjugate): Returns the complex conjugate ofself. -
denominator: Returns the denominator (always positive) of theRationalrepresentation ofself. -
div: Returns the value ofselfdivided by the given value and converted to an integer. -
divmod: Returns array[quotient, modulus]resulting from dividingselfthe given divisor. -
fdiv: Returns theFloatresult of dividingselfby the given divisor. -
floor: Returns the largest number less than or equal toself, to a given precision. -
i: Returns theComplexobjectComplex(0, self). the given value. -
imaginary(aliased asimag): Returns the imaginary part of theself. -
numerator: Returns the numerator of theRationalrepresentation ofself; has the same sign asself. -
polar: Returns the array[self.abs, self.arg]. -
quo: Returns the value ofselfdivided by the given value. -
real: Returns the real part ofself. -
rect(aliased asrectangular): Returns the array[self, 0]. -
remainder: Returnsself-arg*(self/arg).truncatefor the givenarg. -
round: Returns the value ofselfrounded to the nearest value for the given a precision. -
to_int: Returns theIntegerrepresentation ofself, truncating if necessary. -
truncate: Returnsselftruncated (toward zero) to a given precision.
Other
Public Instance Methods
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 196
def %: (Numeric) -> Numeric
Returns self modulo other as a real numeric (Integer, Float, or Rational).
Of the Core and Standard Library classes, only Rational uses this implementation.
For Rational r and real number n, these expressions are equivalent:
r % n r-n*(r/n).floor r.divmod(n)[1]
See Numeric#divmod.
Examples:
r = Rational(1, 2) # => (1/2) r2 = Rational(2, 3) # => (2/3) r % r2 # => (1/2) r % 2 # => (1/2) r % 2.0 # => 0.5 r = Rational(301,100) # => (301/100) r2 = Rational(7,5) # => (7/5) r % r2 # => (21/100) r % -r2 # => (-119/100) (-r) % r2 # => (119/100) (-r) %-r2 # => (-21/100)
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 201
def +: (Numeric) -> Numeric
Performs addition: the class of the resulting object depends on the class of numeric.
() → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 209
def +@: () -> self
Returns self.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 214
def -: (Numeric) -> Numeric
Performs subtraction: the class of the resulting object depends on the class of numeric.
() → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 222
def -@: () -> self
Returns self, negated.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 240
def <=>: (Numeric other) -> Integer
Compares self and other.
Returns:
-
Zero, if
selfis the same asother. -
nil, otherwise.
Class Numeric includes module Comparable, each of whose methods uses Numeric#<=> for comparison.
No subclass in the Ruby Core or Standard Library uses this implementation.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 252
def abs: () -> Numeric
Returns the absolute value of self.
12.abs #=> 12 (-34.56).abs #=> 34.56 -34.56.abs #=> 34.56
() → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 260
def abs2: () -> self
Returns the square of self.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 265
def angle: () -> (0 | Float)
Returns zero if self is positive, Math::PI otherwise.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 287
def ceil: () -> Integer
| (Integer digits) -> (Integer | Numeric)
Returns the smallest float or integer that is greater than or equal to self, as specified by the given ndigits, which must be an integer-convertible object.
Equivalent to self.to_f.ceil(ndigits).
Related: floor, Float#ceil.
(?freeze: true?) → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 831
def clone: (?freeze: true?) -> self
Returns self.
Raises an exception if the value for freeze is neither true nor nil.
Related: Numeric#dup.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 322
def coerce: (Numeric) -> [ Numeric, Numeric ]
Returns a 2-element array containing two numeric elements, formed from the two operands self and other, of a common compatible type.
Of the Core and Standard Library classes, Integer, Rational, and Complex use this implementation.
Examples:
i = 2 # => 2 i.coerce(3) # => [3, 2] i.coerce(3.0) # => [3.0, 2.0] i.coerce(Rational(1, 2)) # => [0.5, 2.0] i.coerce(Complex(3, 4)) # Raises RangeError. r = Rational(5, 2) # => (5/2) r.coerce(2) # => [(2/1), (5/2)] r.coerce(2.0) # => [2.0, 2.5] r.coerce(Rational(2, 3)) # => [(2/3), (5/2)] r.coerce(Complex(3, 4)) # => [(3+4i), ((5/2)+0i)] c = Complex(2, 3) # => (2+3i) c.coerce(2) # => [(2+0i), (2+3i)] c.coerce(2.0) # => [(2.0+0i), (2+3i)] c.coerce(Rational(1, 2)) # => [((1/2)+0i), (2+3i)] c.coerce(Complex(3, 4)) # => [(3+4i), (2+3i)]
Raises an exception if any type conversion fails.
() → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 330
def conjugate: () -> self
Returns self.
() → Integer
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 345
def denominator: () -> Integer
Returns the denominator (always positive).
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 358
def div: (Numeric) -> Integer
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 387
def divmod: (Numeric) -> [ Numeric, Numeric ]
Returns a 2-element array [q, r], where
q = (self/other).floor # Quotient r = self % other # Remainder
Of the Core and Standard Library classes, only Rational uses this implementation.
Examples:
Rational(11, 1).divmod(4) # => [2, (3/1)] Rational(11, 1).divmod(-4) # => [-3, (-1/1)] Rational(-11, 1).divmod(4) # => [-3, (1/1)] Rational(-11, 1).divmod(-4) # => [2, (-3/1)] Rational(12, 1).divmod(4) # => [3, (0/1)] Rational(12, 1).divmod(-4) # => [-3, (0/1)] Rational(-12, 1).divmod(4) # => [-3, (0/1)] Rational(-12, 1).divmod(-4) # => [3, (0/1)] Rational(13, 1).divmod(4.0) # => [3, 1.0] Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
(untyped) → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 408
def eql?: (untyped) -> bool
Returns true if self and other are the same type and have equal values.
Of the Core and Standard Library classes, only Integer, Rational, and Complex use this implementation.
Examples:
1.eql?(1) # => true 1.eql?(1.0) # => false 1.eql?(Rational(1, 1)) # => false 1.eql?(Complex(1, 0)) # => false
Method eql? is different from == in that eql? requires matching types, while == does not.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 421
def fdiv: (Numeric) -> Numeric
Returns the quotient self/other as a float, using method / as defined in the subclass of Numeric. (Numeric itself does not define /.)
Of the Core and Standard Library classes, only BigDecimal uses this implementation.
() → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 429
def finite?: () -> bool
Returns true if self is a finite number, false otherwise.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 443
def floor: () -> Integer
| (Integer digits) -> Numeric
Returns the largest float or integer that is less than or equal to self, as specified by the given ndigits, which must be an integer-convertible object.
Equivalent to self.to_f.floor(ndigits).
Related: ceil, Float#floor.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 458
def i: () -> Complex
Returns Complex(0, self):
2.i # => (0+2i) -2.i # => (0-2i) 2.0.i # => (0+2.0i) Rational(1, 2).i # => (0+(1/2)*i) Complex(3, 4).i # Raises NoMethodError.
() → 0
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 466
def imaginary: () -> 0
Returns zero.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 482
def infinite?: () -> Integer?
Returns nil, -1, or 1 depending on whether self is finite, -Infinity, or +Infinity.
() → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 493
def integer?: () -> bool
Returns true if self is an Integer.
1.0.integer? # => false 1.integer? # => true
Returns the absolute value of self.
12.abs #=> 12 (-34.56).abs #=> 34.56 -34.56.abs #=> 34.56
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 533
def modulo: (Numeric) -> Numeric
Returns self modulo other as a real numeric (Integer, Float, or Rational).
Of the Core and Standard Library classes, only Rational uses this implementation.
For Rational r and real number n, these expressions are equivalent:
r % n r-n*(r/n).floor r.divmod(n)[1]
See Numeric#divmod.
Examples:
r = Rational(1, 2) # => (1/2) r2 = Rational(2, 3) # => (2/3) r % r2 # => (1/2) r % 2 # => (1/2) r % 2.0 # => 0.5 r = Rational(301,100) # => (301/100) r2 = Rational(7,5) # => (7/5) r % r2 # => (21/100) r % -r2 # => (-119/100) (-r) % r2 # => (119/100) (-r) %-r2 # => (-21/100)
() → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 541
def negative?: () -> bool
Returns true if self is less than 0, false otherwise.
() → self?
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 561
def nonzero?: () -> self?
Returns self if self is not a zero value, nil otherwise; uses method zero? for the evaluation.
The returned self allows the method to be chained:
a = %w[z Bb bB bb BB a aA Aa AA A] a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b } # => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
Of the Core and Standard Library classes, Integer, Float, Rational, and Complex use this implementation.
Related: zero?
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 569
def numerator: () -> Numeric
Returns the numerator.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 582
def polar: () -> [ Numeric, Numeric ]
Returns array [self.abs, self.arg].
() → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 590
def positive?: () -> bool
Returns true if self is greater than 0, false otherwise.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 599
def quo: (Numeric) -> Numeric
Returns the most exact division (rational for integers, float for floats).
() → self
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 607
def real: () -> self
Returns self.
() → true
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 615
def real?: () -> true
Returns true if self is a real number (i.e. not Complex).
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 620
def rect: () -> [ Numeric, Numeric ]
Returns array [self, 0].
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 659
def remainder: (Numeric) -> Numeric
Returns the remainder after dividing self by other.
Of the Core and Standard Library classes, only Float and Rational use this implementation.
Examples:
11.0.remainder(4) # => 3.0 11.0.remainder(-4) # => 3.0 -11.0.remainder(4) # => -3.0 -11.0.remainder(-4) # => -3.0 12.0.remainder(4) # => 0.0 12.0.remainder(-4) # => 0.0 -12.0.remainder(4) # => -0.0 -12.0.remainder(-4) # => -0.0 13.0.remainder(4.0) # => 1.0 13.0.remainder(Rational(4, 1)) # => 1.0 Rational(13, 1).remainder(4) # => (1/1) Rational(13, 1).remainder(-4) # => (1/1) Rational(-13, 1).remainder(4) # => (-1/1) Rational(-13, 1).remainder(-4) # => (-1/1)
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 671
def round: () -> Integer
| (Integer digits) -> Numeric
Returns self rounded to the nearest value with a precision of digits decimal digits.
Numeric implements this by converting self to a Float and invoking Float#round.
(?Numeric limit, ?Numeric step) { (Numeric) → void } → self
(?Numeric limit, ?Numeric step) → Enumerator::ArithmeticSequence
(?by: Numeric, ?to: Numeric) { (Numeric) → void } → self
(?by: Numeric, ?to: Numeric) → Enumerator::ArithmeticSequence
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 765
def step: (?Numeric limit, ?Numeric step) { (Numeric) -> void } -> self
| (?Numeric limit, ?Numeric step) -> Enumerator::ArithmeticSequence
| (?by: Numeric, ?to: Numeric) { (Numeric) -> void } -> self
| (?by: Numeric, ?to: Numeric) -> Enumerator::ArithmeticSequence
Generates a sequence of numbers; with a block given, traverses the sequence.
Of the Core and Standard Library classes, Integer, Float, and Rational use this implementation.
A quick example:
squares = [] 1.step(by: 2, to: 10) {|i| squares.push(i*i) } squares # => [1, 9, 25, 49, 81]
The generated sequence:
-
Begins with
self. -
Continues at intervals of
by(which may not be zero). -
Ends with the last number that is within or equal to
to; that is, less than or equal totoifbyis positive, greater than or equal totoifbyis negative. Iftoisnil, the sequence is of infinite length.
If a block is given, calls the block with each number in the sequence; returns self. If no block is given, returns an Enumerator::ArithmeticSequence.
Keyword Arguments
With keyword arguments by and to, their values (or defaults) determine the step and limit:
# Both keywords given. squares = [] 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4 squares # => [16, 36, 64, 100] cubes = [] 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3 cubes # => [27.0, 3.375, 0.0, -3.375, -27.0] squares = [] 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) } squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0] squares = [] Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) } squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0] # Only keyword to given. squares = [] 4.step(to: 10) {|i| squares.push(i*i) } # => 4 squares # => [16, 25, 36, 49, 64, 81, 100] # Only by given. # Only keyword by given squares = [] 4.step(by:2) {|i| squares.push(i*i); break if i > 10 } squares # => [16, 36, 64, 100, 144] # No block given. e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3)) e.class # => Enumerator::ArithmeticSequence
Positional Arguments
With optional positional arguments to and by, their values (or defaults) determine the step and limit:
squares = [] 4.step(10, 2) {|i| squares.push(i*i) } # => 4 squares # => [16, 36, 64, 100] squares = [] 4.step(10) {|i| squares.push(i*i) } squares # => [16, 25, 36, 49, 64, 81, 100] squares = [] 4.step {|i| squares.push(i*i); break if i > 10 } # => nil squares # => [16, 25, 36, 49, 64, 81, 100, 121]
Implementation Notes
If all the arguments are integers, the loop operates using an integer counter.
If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed floor(n + n*Float::EPSILON) + 1 times, where n = (limit - self)/step.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 776
def to_c: () -> Complex
Returns self as a Complex object.
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 795
def to_int: () -> Integer
Returns self as an integer; converts using method to_i in the subclass of Numeric. (Numeric itself does not define to_i.)
Of the Core and Standard Library classes, only Rational and Complex use this implementation.
Examples:
Rational(1, 2).to_int # => 0 Rational(2, 1).to_int # => 2 Complex(2, 0).to_int # => 2 Complex(2, 1).to_int # Raises RangeError (non-zero imaginary part)
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.1.3/core/numeric.rbs, line 807
def truncate: () -> Integer
| (Integer ndigits) -> (Integer | Numeric)
Returns self truncated (toward zero) to a precision of digits decimal digits.
Numeric implements this by converting self to a Float and invoking Float#truncate.