get module names

M

Mario Ruiz

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
 
J

John Morrice

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

From=20
$ 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
=3D> nil
irb(main):005:0> A.methods.sort
=3D>
...here I looked at the list of methods...
irb(main):006:0> A.constants
=3D> [:B]

Wishing you happy learnings,

Johnny
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

Thanks a lot!!! It works!!!
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]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,801
Messages
2,569,658
Members
45,421
Latest member
DoreenCorn

Latest Threads

Top