我有这样的 ruby 代码:
module Hello
class Hi
def initialize()
puts self.module.name //Should print "Hello"
end
end
end
如何获取包含该类的模块的名称? 谢谢
最佳答案
您可以使用Module::nesting来做到这一点方法:
nesting → array
Returns the list of Modules nested at the point of call.
module M
class C
Module.nesting[1] # => M
end
end
如果你想从实例方法中获取这个值,你可以将它分配给类变量:
module Hello
class Hi
@@parent = Module.nesting[1]
def initialize()
puts @@parent # => Hello
end
end
end
关于来自其中定义的类的模块的 Ruby 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8990368/