How do I tell which modules have been mixed into a class?

Try:

MyClass.ancestors.select {|o| o.class == Module }

for example:

>> Array.ancestors.select {|o| o.class == Module}
=> [Enumerable, Kernel]

UPDATE

To get the modules mixed into an object instance at runtime you’ll need to retrieve the eigenclass of the instance. There is no clean way to do this in Ruby, but a reasonably common idiom is the following:

(class << obj; self; end).included_modules

If you find yourself using this a lot, you can make it generally available:

module Kernel
  def eigenclass
    class << self
      self
    end
  end
end

and the solution is then:

obj.eigenclass.included_modules

Leave a Comment