Get module names

I would like to know the module names I have declared in other file but
I don’t know how to do it.
I have in a file this code:
module MyModuleX
module A

end
module B

end


end

and I would like to know which module names I have declared inside
MyModuleX on that file to use the names for other purpose.

Thanks in advance

I would like to know the module names I have declared in other file
but I don’t know how to do it.

From
$ ri Module.constants

(from ruby core)

Module.constants -> array


Returns an array of the names of all constants defined in the system.
This list includes the names of all modules and classes.

Also, I discovered this for myself in about 1 minute with irb, by
doing this:

irb(main):001:0> module A
irb(main):002:1> module B
irb(main):003:2> end
irb(main):004:1> end
=> nil
irb(main):005:0> A.methods.sort
=>
…here I looked at the list of methods…
irb(main):006:0> A.constants
=> [:B]

Wishing you happy learnings,

Johnny

Thanks a lot!!! It works!!!

On Mon, Nov 22, 2010 at 9:14 AM, Mario R. [email protected] wrote:

Thanks a lot!!! It works!!!


Posted via http://www.ruby-forum.com/.

Note that it will give you all constants. You can use a reflection to
get
just the modules.

module MyModuleX
module A ; end
module B ; end
class C ; end
DEF = nil
end

all constants

MyModuleX.constants # => [:A, :B, :C, :DEF]

modules only

instance_of? checks that obj.class == Module

modules = MyModuleX.constants.select do |name|
MyModuleX.const_get(name).instance_of? Module
end
modules # => [:A, :B]

classes and modules

is_a? checks that obj.class.ancestors.include? Module

modules = MyModuleX.constants.select do |name|
MyModuleX.const_get(name).is_a? Module
end
modules # => [:A, :B, :C]