类 Numeric

Numeric 是所有更高级别的数字类应该继承的类。

Numeric 允许实例化堆分配的对象。其他核心数字类,如 Integer,是作为立即数实现的,这意味着每个 Integer 都是一个不可变的单例对象,始终按值传递。

a = 1
1.object_id == a.object_id   #=> true

例如,整数 1 只能有一个实例。Ruby 通过阻止实例化来确保这一点。如果尝试复制,则会返回相同的实例。

Integer.new(1)                   #=> NoMethodError: undefined method `new' for Integer:Class
1.dup                            #=> 1
1.object_id == 1.dup.object_id   #=> true

因此,在定义其他数字类时,应使用 Numeric。

继承自 Numeric 的类必须实现 coerce,它返回一个包含已强制转换为新类实例的对象和 self 的双成员 Array(请参阅 coerce)。

继承类还应实现算术运算符方法(+-*/)和 <=> 运算符(请参阅 Comparable)。这些方法可能依赖于 coerce 来确保与其他数字类实例的互操作性。

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

这里有什么

首先,看看其他地方的内容。类 Numeric

在这里,类 Numeric 提供了以下方法:

查询

比较

转换

其他