覆盖BigDecimal的to_s在Ruby中默认 [英] Override BigDecimal to_s default in Ruby

查看:151
本文介绍了覆盖BigDecimal的to_s在Ruby中默认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从数据库表中检索数据的数组被填充。一些字段被定义为小数&放大器;钱场和阵列内,他们正在重新psented为BigDecimal的$ P $。

As I retrieve data from a database table an array is populated. Some of the fields are defined as decimal & money fields and within the array they are represented as BigDecimal.

我用这些数组值来填充一个CSV文件,但问题是,所有的BigDecimal值默认情况下重新$ P $以科学格式psented(这是BigDecimal的to_s方法的默认行为)。我可以通过使用to_s(F)显示的值,但我怎么能覆盖默认的?

I use these array values to populate a CSV file, but the problem is that all BigDecimal values are by default represented in Scientific format (which is the default behaviour of the BigDecimal to_s method). I can show the values by using to_s('F'), but how can I override the default?

推荐答案

这是建立在@法雷尔的答案,但没有一个无用的 old_xyz 法污染的方法命名空间。另外,为什么不直接使用默认参数?

This is built on @Farrel's answer, but without polluting the method namespace with a useless old_xyz method. Also, why not use default arguments directly?

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,这得稍稍丑陋:

In Ruby 1.8, this gets slightly uglier:

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

或者,如果你不喜欢你上述code得到警告:

Or, if you don't like the warning you get with the above code:

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

这篇关于覆盖BigDecimal的to_s在Ruby中默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆