当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Ruby Numeric类用法及代码示例

本文简要介绍ruby语言中 Numeric类 的用法。

Numeric 是所有高级数值类都应继承的类。

Numeric 允许实例化 heap-allocated 对象。其他核心数值类,例如 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 ,它返回一个 two-member Array ,其中包含一个已被强制转换为新类实例的对象和 self (参见 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

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Numeric类。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。