作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
<分区>
Possible Duplicate:
In Ruby is there a way to overload the initialize constructor?
BigDecimal
初始值不采用 float ,因此我正在编写一个构造函数来处理它。好像是忽略了初始化方法,调用了默认构造函数。
它抛出TypeError can't convert Float into String (TypeError)
format
方法确实有效。
文件 BigDecimal.rb:
require 'bigdecimal'
class BigDecimal
def initialize
if self.class == Float
super self.to_s
end
end
def format
sprintf("%.2f", self)
end
end
然后,在文件 test.rb 中:
require 'BigDecimal' # => true
bd = BigDecimal.new('54.4477') # works
puts bd.format # 54.44
bd2 = BigDecimal.new(34.343) # TypeError: can't convert Float into String (TypeError)
ruby 1.9.2
我是一名优秀的程序员,十分优秀!