gpt4 book ai didi

ruby - 如何在 Ruby 中重载构造函数?

转载 作者:数据小太阳 更新时间:2023-10-29 08:16:00 25 4
gpt4 key购买 nike

<分区>

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com