What is `singleton_class` method in class and object?

284 views Asked by At

I defined methods specific_data1 and specific_data2 in meta class, and expected these methods belong to the singleton class:

class User
  def User.specific_data1
    "user specific data defined on user"
  end
  class << self
    def specific_data2
      "user specific data defined in meta class"
    end
  end
end

But neither of the methods is found in:

User.singleton_class.methods

Please help me understand what singleton_method on User class is and how it is useful.

3

There are 3 answers

4
Jörg W Mittag On BEST ANSWER

Object#methods returns the methods of that object. Methods defined in a class aren't methods of that class object, they are methods of that class's instances.

This has nothing to do with singleton classes, it's true for all classes:

class Foo
  def bar; end
end

Foo.methods.include?(:bar)
# => false

Foo.new.methods.include?(:bar)
# => true

Foo.instance_methods
# => [:bar]

Here's how that works with your example:

User.methods.grep(/specific/)
# => [:specific_data1, :specific_data2]

User.singleton_methods
# => [:specific_data1, :specific_data2]

User.singleton_class.instance_methods.grep(/specific/)
# => [:specific_data1, :specific_data2]
0
egwspiti On

Both of the methods you defined are defined as instance methods on the singleton_class.

User.singleton_class.instance_methods(false)
# => [:specific_data1, :specific_data2]
0
Max On

Jorg got the technical part of your question right. You want to check

User.singleton_class.instance_methods

As for this

Please help me understand what singleton_method on User class is and how it is useful."

Suppose you have an object x and you want to define a method for it. One way would be to define the method in x's class, but this has the side effect of defining the method for all other objects of that class! What if you just want to define the method for the single object x?

Ruby solves this problem by letting you create a class which has only a single instance: x. This is the singleton class. Methods defined in it will only affect x because the singleton class is a subclass of x.class and its only instance is x. Singleton methods are just regular methods defined in a singleton class.