# Getting all classes within a module?

**URL:** https://rubytalk.org/t/getting-all-classes-within-a-module/1988
**Category:** ruby-talk
**Created:** [25 September 2002 21:43 UTC](https://rubytalk.org/t/getting-all-classes-within-a-module/1988 "2002-09-25T21:43:53Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Markus\_Jais](https://avatars.discourse-cdn.com/v4/letter/m/858c86/32.png) [@Markus\_Jais](https://rubytalk.org/u/Markus_Jais)
#### Post date: [25 September 2002 21:43 UTC](https://rubytalk.org/t/getting-all-classes-within-a-module/1988/1 "2002-09-25T21:43:53Z")

</div>

hello

is there a way to get all classes defined within a module ?

something like this:

require "mymodule"  
classes = mymodule.classes\_within\_this\_module

markus

---

<div class="post-metadata">

### Author: ![Joel\_VanderWerf1](https://avatars.discourse-cdn.com/v4/letter/j/94ad74/32.png) [@Joel\_VanderWerf1](https://rubytalk.org/u/Joel_VanderWerf1)
#### Post date: [25 September 2002 22:44 UTC](https://rubytalk.org/t/getting-all-classes-within-a-module/1988/2 "2002-09-25T22:44:42Z")

</div>

Markus Jais wrote:

> hello
> 
> is there a way to get all classes defined within a module ?
> 
> something like this:
> 
> require “mymodule”  
> classes = mymodule.classes\_within\_this\_module

```
         ^^^^^^^^ what is this?

```

In ruby, modules and files are different things, though they are often  
in a one-to-one correspondence. I’ll assume that you are interested in  
modules.

The following will give you all the classes defined in the scope of String.

String.constants.map {|x| String.const\_get x}.grep(Class)

But this includes things like Float that are defined in Object. So let’s  
define:

class Module  
def my\_classes  
constants.map {|x| const\_get x}.grep(Class)  
end  
end

Then you can do

String.my\_classes - String.superclass.my\_classes

which will be empty, unless you add a class in String:

class String  
class S; end  
end

after which the subtraction will return:

[String::S]

One more twist: you may also want to subtract constants that come from a  
mixin module.

module Enumerable  
class E  
end  
end

String.my\_classes - String.superclass.my\_classes

# ==\> [String::S, Enumerable::E]

So let’s define:

class Module  
def my\_own\_classes  
my\_classes - ancestors.map {|a|  
(a == self)? : a.my\_classes  
}.flatten  
end  
end

String.my\_own\_classes

# ==\> [String::S]
