从Ruby中的父类实例化子类的实例

时间:2014-05-05 04:22:53

标签: ruby inheritance instantiation class-method

如果我有一个继承自A类的B类,我可以通过A类中定义的类方法实例化B类吗?

class A
  def self.instantiate params
    # ???
  end
end

class B < A
end

b = B.instantiate 123
b.class   # => B

显然,我不想从A调用B.new。任何继承自A的类都应该从中受益。

class C < A; end
c = C.instantiate 123
c.class   # => C

class D < A; end
d = D.instantiate 123
d.class   # => D

1 个答案:

答案 0 :(得分:1)

只需调用self.newself在类方法中引用类本身):

class A
  def self.instantiate params
    self.new
    # OR simply `new`
  end
end

class B < A; end
b = B.instantiate 123
b.class
# => B

class C < A; end
c = C.instantiate 123
c.class
# => C

class D < A; end
d = D.instantiate 123
d.class
# => D

<强>更新

正如Cary Swoveland评论的那样,你可以省略self.

  def self.instantiate params
    new
  end