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

标签 ruby constructor overloading ruby-1.9.2 overriding

<分区>

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

最佳答案

你的代码有问题:

  1. 您使用猴子补丁而不是继承,因此在您的initialize 方法中,super 将调用Object 的初始化方法,它是 BigDecimal 的父类(super class)。要调用默认构造函数,您必须使用如下所示的其他方法。

  2. 您没有为 initialize 方法添加参数。

  3. BigDecimal 确实将 float 作为构造函数参数

因此,

  1. 您可以直接使用默认构造函数并传递一个 float :

    BigDecimal.new(34.343, 5) # 5 is the precision
    
  2. 您可以通过这种方式覆盖构造函数:

注意:我们通常为initialize 方法起别名。然而在这种情况下,这似乎不起作用(由于某些未知原因 initialize 没有被调用)......所以我们必须为 new 方法起别名,这是更基本的.

    require 'bigdecimal'

    class BigDecimal

        class << self
          alias_method :__new__, :new  #alias the original constructor so we can call later
          def new(*args)
              if args.length == 1 && args[0].is_a?(Float)
                  __new__(args[0].to_s)
              else
                  __new__(*args)
              end
          end
        end

        def format
            sprintf("%.2f", self)
        end

    end

    BigDecimal.new(12.334)
    #<BigDecimal:10a9a48,'0.12334E2',18(18)>

关于ruby - 如何在 Ruby 中重载构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11141980/

相关文章:

c++ - void 和非 void 返回函数的完美转发

ruby-on-rails - ruby rails : re-order checkbox tag

javascript - 创建电子表格

Ruby NET::SCP 和自定义端口

c# - 使用构造函数从 dapper 获取非原始类型的对象

actionscript-3 - Actionscript-3 中静态构造函数的语法?

c++ - 二叉树 - 复制构造函数

java - 关于Java重载和动态绑定(bind)的问题

ruby-on-rails - Thinking sphinx - 带条件连接的索引 (has_and_belongs_to_many)

java - 使用可变参数重载函数