Advanced Ruby: metaclasses

Posted by Daniel Vela on May 20, 2020

Advance Ruby: metaclasses

Each object in Ruby has a hidden class. Even classes in Ruby, that are also objects, have a hidden class associated.

class Person
  def name(n)
    @name = n

thisjs =  # => :name
thisjs.class  # => Person
thisjs.singleton_class  # => #<Class:#<Person:0x00007f9c8fb302a8>>

You can add methods to the metaclass of an instance with:

juan ="Juan")

def juan.last_name 

juan.last_name  # => "Perez"

tom =
tom.last_name  # => NoMethodError (undefined method `last_name' for #<Person:0x00007f9c8f085650>)

Adding a method to the metaclass of an object doesn’t add that method to the class of that object.