Override BigDecimal to_s default in Ruby

末鹿安然 提交于 2020-01-02 09:43:27

问题


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.

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?


回答1:


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

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

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



回答2:


class BigDecimal
  alias old_to_s to_s

  def to_s( param = nil )
      self.old_to_s( param || 'F' )
   end
end



回答3:


Ruby makes this easy. Behold:

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.

This technique is called monkey patching. As you might guess from the name, it's something you should use cautiously. This use seems reasonable to me, though.



来源:https://stackoverflow.com/questions/2335034/override-bigdecimal-to-s-default-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!