02 fevereiro 2015

Ruby: Singleton Class

Every object in ruby is associated with two classes: The class which instantiated it and an anonymous class. The anonymous class is called "singleton class".
You're probably familiar with this kind of code:
class Person
  class << self
    def count
      @count ||= 0
    end
  end
end

which is the same as:

class Person
  def self.count
    @count ||= 0
  end
end

Everything time we inject a method into an object, they are added as singleton methods. But you should know that those methods belong only to the object in which they were defined.

string = 'bernardofire'
another_string = 'foobar'

def string.first_letter
  self[0]
end

string.first_letter #=> "b"
another_string.respond_to?(:first_letter) #=> false

We can also use Object#singleton_methods to prove that #first_letter is a singleton method:
string.singleton_methods
#=> ["first_letter"]

another_string.singleton_methods
#=> []