Skip to content

Instantly share code, notes, and snippets.

@yaquawa
Last active July 7, 2019 08:37
Show Gist options
  • Save yaquawa/08f5bea7cd9bb7b4715410c682f66ca5 to your computer and use it in GitHub Desktop.
Save yaquawa/08f5bea7cd9bb7b4715410c682f66ca5 to your computer and use it in GitHub Desktop.
Decode Ruby's `Singleton-Class` with example

The singleton methods of an object are not defined by the class of that object. But they are methods and they must be associated with a class of some sort. The singleton methods of an object are instance methods of the anonymous singleton-class(eigenclass) associated with that object.

To open the singleton-class of the object obj, use class << obj

class Object
  # Get the singleton-class object of a class object. 
  def singleton_class
    class << self #Open the singleton-class of `self`
    
      # When you open the singleton-class of an object,
      # `self` refers to the anonymous singleton-class object.
      self
    end
  end
end

class Foo
  # Define singleton-method
  def self.singleton_method_1
  end

  # Another way to define singleton-method
  class << self
    def singleton_method_2
    end
  end

  def instance_method_1
  end

  a = p self.singleton_class.instance_methods(false) # => [:singleton_method_1, :singleton_method_2]
  b = p self.methods(false) # => [:singleton_method_1, :singleton_method_2]
  
  # So called 'class methods' are just the instance methods of it's associated singleton-class.
  p a==b # => true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment