Determining Singleton Class Status in Ruby

Q: How do you tell if a given class is an ordinary class or a singleton class?

A: Test whether the class is the first element in its own ancestor list.

class NotASingleton
  self == ancestors.first       # => true
end

class << Object.new
   self == ancestors.first       # => false
end

As you can see, ordinary classes have themselves as first ancestor. Singleton classes do not have themselves as an ancestor.

This entry was posted in Howto, Ruby and tagged , , , . Bookmark the permalink.
  • Piers Cawley

    Why would you ever need to know?

    • http://wideteams.com Avdi Grimm

      It's important for certain metaprogramming tasks. If I've defined a module that does some metaprogramming when it is included in a class, it may need to know if it has been included in a singleton class or a “normal” class (or another module).