Module children

Hello,

I’d like to get the list of all the classes contained in a module.
What’s the simple way to do that?

Thank you

On Feb 1, 8:50 pm, Camille R. [email protected] wrote:

Hello,

I’d like to get the list of all the classes contained in a module.
What’s the simple way to do that?

Thank you

Posted viahttp://www.ruby-forum.com/.

Here’s a quick and dirty implementation using ObjectSpace

module LibraryWrapperThing
class UtilityClassA; end
class Fish; end
class Dog; end
end
class NotMe; end

classes = []
ObjectSpace.each_object do |obj|
classes << obj if Module === obj
end

p classes.select {|c| c.name =~ /^LibraryWrapperThing::confused: }

=> [LibraryWrapperThing::Dog, LibraryWrapperThing::Fish, …]

On Tue, Feb 02, 2010 at 04:50:34AM +0900, Camille R. wrote:

Hello,

I’d like to get the list of all the classes contained in a module.
What’s the simple way to do that?

module Foo; A = 1; class B; end; module C; end end
=> nil

Foo.constants.find_all { |k| Class === Foo.const_get(k) }
=> [“B”]

On Feb 1, 10:06 pm, Aaron P. [email protected]
wrote:

module Foo; A = 1; class B; end; module C; end end
=> nil
Foo.constants.find_all { |k| Class === Foo.const_get(k) }

=> [“B”]

+1 :slight_smile:

On Feb 1, 2010, at 13:06 , Aaron P. wrote:

On Tue, Feb 02, 2010 at 04:50:34AM +0900, Camille R. wrote:

Hello,

I’d like to get the list of all the classes contained in a module.
What’s the simple way to do that?

module Foo; A = 1; class B; end; module C; end end
=> nil

Foo.constants.find_all { |k| Class === Foo.const_get(k) }
=> [“B”]

Personally, I usually map first:

Foo.constants.map { |s| Foo.const_get s }.find_all { |k| Class === k }
=> [Foo::B]

On Feb 1, 2010, at 13:55 , James Edward G. II wrote:

=> [Foo::B]
Ah! I always forget about that one. Good catch.

On Feb 1, 2010, at 3:38 PM, Ryan D. wrote:

=> nil

Foo.constants.find_all { |k| Class === Foo.const_get(k) }
=> [“B”]

Personally, I usually map first:

Foo.constants.map { |s| Foo.const_get s }.find_all { |k| Class === k }
=> [Foo::B]

Then you can switch the the under loved grep():

Foo.constants.map { |s| Foo.const_get s }.grep(Class)
=> [Foo::B]

James Edward G. II