The Ruby Object Model
19.1 Core Ideas
Every object has a class. Classes are objects (instances of Class). Class inherits from Module → Object → BasicObject.
Every object can have a singleton class (eigenclass) holding its own methods. Class methods are singleton methods of the class object.
String.class # Class
Class.superclass # Module
Module.superclass # Object
Object.superclass # BasicObject
BasicObject.superclass # nil
str = "hi"
def str.shout = upcase + "!" # singleton method
str.singleton_methods # [:shout]
str.singleton_class # #<Class:#<String:...>>
String.singleton_class.instance_methods(false)19.2 Diagram
BasicObject
▲
Object ◄── Kernel (module)
▲
Module ◄──── Class
▲
User (class) ──singleton──► #<Class:User> (holds class methods)
▲
user (instance) ──singleton──► #<Class:#<User>> (holds per-object methods)19.3 self in Different Contexts
main (an instance of Object) Inside a class body The class itself Inside an instance method Inside def self.x Inside class << self The singleton class Inside a block
Whatever self was where the block was defined (unless instance_eval/instance_exec)
19.4 Top-Level Methods and main
Methods defined at the top level become private methods of Object, so they're callable everywhere.
19.5 BasicObject
class BlankSlate < BasicObject # minimal object: no Kernel methods (used for proxies/DSLs)
def method_missing(name, *args) = "called #{name}"
def respond_to_missing?(*) = true
end