简体   繁体   English

ruby - 返回当前类的实例

[英]ruby - return an instance of current class

I noticed if I make a subclass which inherits from Datetime , it's .now will return the subclass instance, not Datetime instance. 我注意到如果我创建一个继承自Datetime的子类,它的.now将返回子类实例,而不是Datetime实例。

class MyDateTime < DateTime
end

MyDateTime.now
>#<MyDateTime: 2012-06-05T16:42:57+08:00 ((2456084j,31377s,900801494n),+28800s,2299161j)>

It seems magical. 看起来很神奇。 I can't reproduce this behavior in my own class: 我不能在我自己的类中重现这种行为:

class A
  def self.a
   return A.new
  end
end

class B < A
end

B.a
#<A:0x00000001e22358>

I tried to read the source code of DateTime but it's written in C. Is it possible to write a class method which returns an instance of the class it belongs to? 我试图读取DateTime的源代码,但它是用C语言编写的。是否可以编写一个类方法来返回它所属的类的实例?

Try it with self: 尝试自己:

class A
  def self.a
   return self.new
  end
end

class B < A
end

B.a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM