如何从扩展类中的类方法或包含的模块中访问父类的字符串名称

时间:2022-04-05 23:18:01

My problem basically looks like this:

我的问题基本上是这样的:

module Foo
  class Bar
    def self.who
      self.class.to_s
    end
  end
end

class World < Foo::Bar

end

When I call World.who I don't get "World" as a result, I get "Class". Some quick Googling didn't yield anything useful, so hence I'm here hoping someone will know how to get the correct class name :)

当我叫世界。我没有得到“世界”的结果,我得到了“阶级”。一些快速的谷歌搜索没有产生任何有用的东西,因此我希望有人知道如何获得正确的类名:)

2 个解决方案

#1


4  

If you're calling foo.bar then inside the bar method the value of self will be foo. So when you call World.who the value of self inside who is World. Since World is a class, World.class will return Class, so that's what you get.

如果你调用foo。在bar方法中self的值是foo。所以当你打电话给世界。谁是自我的价值,谁就是世界。因为世界是一个阶级,世界。类会返回类,这就是你得到的。

To get back "World" just call self.to_s or self.name (or just to_s or name).

想要回到“世界”,只需呼唤自我。to_s或self。name(或to_s或name)。

#2


2  

You get that because World is a Class. In ruby, AClass.class != AClass. So, you could use this:

因为世界是一个阶级。在ruby中,AClass。类! = AClass。你可以用这个:

module Foo
  class Bar
    def self.who
      to_s
    end
  end
end

class World < Foo::Bar

end

#1


4  

If you're calling foo.bar then inside the bar method the value of self will be foo. So when you call World.who the value of self inside who is World. Since World is a class, World.class will return Class, so that's what you get.

如果你调用foo。在bar方法中self的值是foo。所以当你打电话给世界。谁是自我的价值,谁就是世界。因为世界是一个阶级,世界。类会返回类,这就是你得到的。

To get back "World" just call self.to_s or self.name (or just to_s or name).

想要回到“世界”,只需呼唤自我。to_s或self。name(或to_s或name)。

#2


2  

You get that because World is a Class. In ruby, AClass.class != AClass. So, you could use this:

因为世界是一个阶级。在ruby中,AClass。类! = AClass。你可以用这个:

module Foo
  class Bar
    def self.who
      to_s
    end
  end
end

class World < Foo::Bar

end