Is there a way to list the classes defined in a module?

  • Thread starter Michael Winterstein
  • Start date
M

Michael Winterstein

Suppose I have a module that's essentially used as a namespace, like
this:

module Castle

class King < Royalty; end

class Queen < Royalty; end

class Guard < Commoner; end

class Dragon_keeper < Commoner; end

end


Is there some way I could later create a list, say Castle_dwellers that
would come out with all the classes defined therein? I would expect an
array, something like [:King,:Queen,:Guard,:Dragon_keeper]. Or would I
have to add them 'manually' to the list?
 
B

burke

Castle.constants

Pretty much. This will also return any other constants you make in the
namespace -- for example, if you had Castle::Location = "Scotland",
you'd also get "Location" back. If that causes you problems, you can
do:

irb(main):034:0> Castle.constants.select{|e|Castle.const_get
(e).kind_of? Class}
=> ["King", "Guard", "Queen", "Dragon_keeper", "Royalty", "Commoner"]
 

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,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top