Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all types declared by module in Ruby

Tags:

ruby

How can I list all the types that are declared by a module in Ruby?

like image 890
readonly Avatar asked Sep 26 '08 01:09

readonly


People also ask

What are modules in Ruby?

A Ruby module is nothing more than a grouping of objects under a single name. The objects may be constants, methods, classes, or other modules. Modules have two uses. You can use a module as a convenient way to bundle objects together, or you can incorporate its contents into a class with Ruby's include statement.

How do you access a module method in Ruby?

To access the instance method defined inside the module, the user has to include the module inside a class and then use the class instance to access that method.

How do you call a method in a module in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

What is class and module in Ruby?

Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables). Modules may be mixed in to classes and other modules.


2 Answers

Use the constants method defined in the Module module. From the Ruby documentation:

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.

p Module.constants.sort[1..5]

produces:

["ARGV", "ArgumentError", "Array", "Bignum", "Binding"]

You can call constants on any module or class you would like.

p Class.constants
like image 163
Bruno Gomes Avatar answered Sep 28 '22 08:09

Bruno Gomes


Not sure if this is what you mean, but you can grab an array of the names of all constants and classes defined in a module by doing

ModuleName.constants

like image 33
zackola Avatar answered Sep 28 '22 09:09

zackola