Advanced Ruby: Object-Specific Classes

Posted by Daniel Vela on May 2, 2020

Advance Ruby: Object-Specific Classes

In Ruby you can create a class tied to an specific object. With this mechanism you can include methods to an existing object.

Sample:

a = "Hello World!"

class << a
  def to_s
    "The value is '#{self}'"
  end
end

a.to_s  # "The values is 'Hellow World!'"

The notation class « obj allows us to include new methods to the object obj.