如果我有一个继承自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
答案 0 :(得分:1)
只需调用self.new
(self
在类方法中引用类本身):
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