Ruby module name from a class defined in

I have ruby ​​code like this:

module Hello

  class Hi

    def initialize()
      puts self.module.name //Should print "Hello"
    end

  end
end

      

How can I get the name of the module that the class is in? Thanks to

+2


source to share


1 answer


You can do this with the Module :: nesting method :

nesting -> array

Returns a list of modules nested within the caller.

module M
  class C
    Module.nesting[1] # => M
  end
end

      



If you want to get this value from instance methods, you can assign it to a class variable:

module Hello    
  class Hi
    @@parent = Module.nesting[1]

    def initialize()
      puts @@parent # => Hello
    end
  end
end

      

+3


source







All Articles