Ruby Language Singleton Class Introduction

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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 # => Class
Class.class   # => Class

Objects themselves can't contain methods, only their class can. But with singleton classes, it is possible to add methods to any object including other singleton classes.

def object.foo
  :foo
end
object.foo #=> :foo

foo is defined on singleton class of object. Other Example instances can not reply to foo.

Ruby creates singleton classes on demand. Accessing them or adding methods to them forces Ruby to create them.



Got any Ruby Language Question?