Tutorial by Examples

Ruby has three types of objects: Classes and modules which are instances of class Class or class Module. Instances of classes. Singleton Classes. Each object has a class which contains its methods: class Example end object = Example.new object.class # => Example Example.class # ...
There are two ways to get singleton class of an object singleton_class method. Reopening singleton class of an object and returning self. object.singleton_class singleton_class = class << object self end
Singleton classes share their instance/class variables with their object. class Example @@foo = :example end def Example.foo class_variable_get :@@foo end Example.foo #=> :example class Example def initialize @foo = 1 end def foo @foo end end e = Ex...
Subclassing also Subclasses Singleton Class class Example end Example.singleton_class #=> #<Class:Example> def Example.foo :example end class SubExample < Example end SubExample.foo #=> :example SubExample.singleton_class.superclass #=> #<Class:Example> ...
Instances never contain a method they only carry data. However we can define a singleton class for any object including an instance of a class. When a message is passed to an object (method is called) Ruby first checks if a singleton class is defined for that object and if it can reply to that mess...
There are three ways to reopen a Singleton Class Using class_eval on a singleton class. Using class << block. Using def to define a method on the object's singleton class directly class Example end Example.singleton_class.class_eval do def foo :foo end end Example.fo...
All objects are instances of a class. However, that is not the whole truth. In Ruby, every object also has a somewhat hidden singleton class. This is what allows methods to be defined on individual objects. The singleton class sits between the object itself and its actual class, so all methods defi...

Page 1 of 1