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
  end
end

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

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

juan = Person.new
juan.name("Juan")

def juan.last_name 
  "Perez"
end

juan.last_name  # => "Perez"

tom = Person.new
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.