开发者

How do I access the string name of the parent class from a class method in a extended class or included module

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 开发者_JS百科hoping someone will know how to get the correct class name :)


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.

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


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

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

class World < Foo::Bar

end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜