【问题标题】:Getting the class name from within the initialize method when class inherited from Hash当类从哈希继承时,从初始化方法中获取类名
【发布时间】:2011-09-27 12:41:43
【问题描述】:

我有一个继承自 Hash 的类。当这个类本身被继承时,我想从initialize 方法中知道继承类的类名。当我调用self 时,我得到{},它不知道name 方法。

class Foo < Hash
  def initialize
    # Here i want to know that the class is Foo
  end
end

如何获取班级名称?

【问题讨论】:

    标签: ruby introspection


    【解决方案1】:

    很简单:self.class.name

    【讨论】:

      【解决方案2】:

      如果您想进行检查,Daniel Brockman 的回答会返回字符串:

      if self.kind_of?(Foo)
        #whatever you want
      end
      

      事情是由于初始化程序的意图,当您调用 Foo.new 时,实例将始终是类 Foo 或子类的实例,所以我对您要做什么感到困惑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-14
        • 1970-01-01
        • 2020-02-11
        相关资源
        最近更新 更多