在Ruby中覆盖BigDecimal to_s默认值

当我从数据库表中检索数据时,会填充一个数组。 一些字段定义为十进制和货币字段,在数组中它们表示为BigDecimal。

我使用这些数组值来填充CSV文件,但问题是默认情况下所有BigDecimal值都以科学格式表示(这是BigDecimal to_s方法的默认行为)。 我可以使用to_s(’F’)显示值,但是如何覆盖默认值?

这是基于@Farrel的答案,但没有使用无用的old_xyz方法污染方法命名空间。 另外,为什么不直接使用默认参数?

 class BigDecimal old_to_s = instance_method :to_s define_method :to_s do |param='F'| old_to_s.bind(self).(param) end end 

在Ruby 1.8中,这有点丑陋:

 class BigDecimal old_to_s = instance_method :to_s define_method :to_s do |param| old_to_s.bind(self).call(param || 'F') end end 

或者,如果您不喜欢上面代码中出现的警告:

 class BigDecimal old_to_s = instance_method :to_s define_method :to_s do |*param| old_to_s.bind(self).call(param.first || 'F') end end 
 class BigDecimal alias old_to_s to_s def to_s( param = nil ) self.old_to_s( param || 'F' ) end end 

Ruby使这很容易。 看吧:

 class BigDecimal def to_s return "Whatever weird format you want" end end # Now BigDecimal#to_s will do something new, for all BigDecimal objects everywhere. 

这种技术称为猴子修补。 正如您可能从名称中猜到的那样,您应谨慎使用它。 不过,这种用法对我来说似乎很合理。