当类继承自 Hash 时,从初始化方法中获取类名
我有一个继承自 Hash
的类。当这个类本身被继承时,我想从 initialize
方法中知道继承类的类名。当我调用 self
时,我得到 {}
,它不知道 name
方法。
class Foo < Hash
def initialize
# Here i want to know that the class is Foo
end
end
我如何获得班级名称?
I have a class that inherits from Hash
. When this class itself gets inherited from, I want to know the class name of the inheriting class from within the initialize
method. When I call self
I get {}
, which doesn't know of the name
method.
class Foo < Hash
def initialize
# Here i want to know that the class is Foo
end
end
How do I get the class name?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
非常简单:
self.class.name
It’s very simple:
self.class.name
如果您想进行检查,Daniel Brockman 的答案将返回字符串:
这是由于初始化程序的意图,当您调用 Foo.new 时,实例将始终是 Foo 类或子类的实例,所以我'我对你想要做什么感到困惑。
Daniel Brockman's answer will return you the string if you want to do a check:
The thing is due to the intent of the initializer, when you call Foo.new the instance will always be an instance of the class Foo or child, so I'm confused about what you're trying to do.