The syntax class << some_objct
opens up some_object
's singleton class, which is a special "secret" class that only that object belongs to. Using the singleton class, you can define methods one object responds to while other instances of its normal class do not.
So, for example:
a = "Hello world"
b = "Hello world" # Note that this is a different String object
class << a
def first_letter
self[0,1]
end
end
puts a.first_letter # prints "H"
puts b.first_letter # Raises an error because b doesn't have that method
In a class context, these two method definitions are equivalent:
class Foo
def self.bar
puts "Yo dawg"
end
end
class Foo
class << self
def bar
puts "Yo dawg"
end
end
end
The second form can be useful in certain circumstances (such as when you want to declare attr_accessor
s for the class object itself).