本文簡要介紹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 Numeric truncate()用法及代碼示例
- Ruby Numeric rect()用法及代碼示例
- Ruby Numeric.i用法及代碼示例
- Ruby Numeric angle()用法及代碼示例
- Ruby Numeric phase()用法及代碼示例
- Ruby Numeric div()用法及代碼示例
- Ruby Numeric integer()用法及代碼示例
- Ruby Numeric positive?用法及代碼示例
- Ruby Numeric.eql?用法及代碼示例
- Ruby Numeric conjugate()用法及代碼示例
- Ruby Numeric finite?()用法及代碼示例
- Ruby Numeric abs()用法及代碼示例
- Ruby Numeric remainder()用法及代碼示例
- Ruby Numeric.coerce用法及代碼示例
- Ruby Numeric ceil()用法及代碼示例
- Ruby Numeric.self % other用法及代碼示例
- Ruby Numeric abs2()用法及代碼示例
- Ruby Numeric.magnitude用法及代碼示例
- Ruby Numeric real?用法及代碼示例
- Ruby Numeric round()用法及代碼示例
- Ruby Numeric.to_int用法及代碼示例
- Ruby Numeric conj()用法及代碼示例
- Ruby Numeric to_int()用法及代碼示例
- Ruby Numeric i()用法及代碼示例
- Ruby Numeric divmod()用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Numeric類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。