class 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 提供了用于以下方面的方

查询

比较

转换

其他