Ruby中的整数和其他(?)抽象类

时间:2015-06-24 13:08:13

标签: ruby

我承认在鸭子打字语言中,抽象类并没有经常使用,所以这个问题更多的是出于好奇而不是实际需要:

在Ruby(至少2.0)中,FixnumBignum有一个名为Integer的公共超类。在我看来,这是一个抽象的类;至少,它不能被实例化,即当你在irb:

irb(main):047:0> Integer.new(8)
NoMethodError: undefined method `new' for Integer:Class
    from (irb):47
    from /usr/bin/irb:12:in `<main>'

现在,如果我决定推出自己的类似Integer的类,即&#34;抽象为Integer是&#34;,我该如何做?我认为每个类都包含一个(隐藏的)new方法(如果存在,则调用我的initialize方法。)

1 个答案:

答案 0 :(得分:5)

您可以取消定义类undef_method上调用singleton classnew类方法,例如:

class Foo
  class << self
    undef_method(:new)
  end
end

Foo.new
# NoMethodError: undefined method `new' for Foo:Class

或者:

class Foo; end
Foo.singleton_class.send(:undef_method, :new)

更新:为了完整起见,这里是@tadman在评论中提到的问题的快速(可能是肮脏的)解决方案。它使用inherited方法为new的子类定义Foo单例方法,该方法模仿Class#new的实现:

class Foo
  class << self
    undef_method(:new)

    def inherited(subclass)
      subclass.define_singleton_method(:new) do |*args|
        obj = subclass.allocate
        obj.send(:initialize, *args)
        obj
      end
    end
  end

end

class Bar < Foo
  attr_reader :bar
  def initialize(bar)
    @bar = bar
  end
end

Bar.new('foobar').bar # => "foobar"