Also, i htink a confusing use of the term is "Singleton object", which is different concept. A singleton object comes from a class which has its constructor/instantiator method overridden so that you can allocate only one of that class.
Instance methods are methods of a class (i.e. defined in the class's definition). Class methods are singleton methods on the Class instance of a class -- they are not defined in the class's definition. Instead, they are defined on the singleton class of the object.
You open the singleton class of an object with the syntax class << obj. Here, we see that this singleton class is where the singleton methods are defined:
methods must always belong to a class (or: be instance methods of some class)
normal methods belong to the class they're defined in (i.e. are instance methods of the class)
class methods are just singleton methods of a Class
singleton methods of an object are not instance methods of the class of the object; rather, they are instance methods of the singleton class of the object.
Ruby provides a way to define methods that are specific to a particular object and such methods are known as Singleton Methods. When one declares a singleton method on an object, Ruby automatically creates a class to hold just the singleton methods. The newly created class is called Singleton Class.
foo = Array.new
def foo.size
"Hello World!"
end
foo.size # => "Hello World!"
foo.class # => Array
#Create another instance of Array Class and call size method on it
bar = Array.new
bar.size # => 0
Singleton class is object specific anonymous class that is automatically created and inserted into the inheritance hierarchy.
singleton_methods can be called on an object to get the list of of names for all of the singleton methods on an object.
A singleton class in the simplest terms is a special class ruby whips up to host methods defined on individual objects. In ruby, it is possible to define methods on individual objects that are unique to that object alone. For instance consider the following below
class User; end
user = User.new
def user.age
"i'm a unique method"
end
user1 = User.new
user.age #"i'm a unique method"
user1.age # NoMethodError (undefined method `age' for #<User:0x0000559c66ab7338>)
As you can see above, user1 object does not respond to the 'age' method because it is a singleton method, a method uniquely defined on user object. For this to happen, ruby creates a special class, called singleton class, or eigenclass, to host this unique method. You can verify this by doing the following:
You can also ask ruby whether the 'age' method is found here by using the method object to find out where the method 'age' is defined. When you do this you will see that singleton class has that method.