Are class method and singleton method doing the same or different? Here is an example.
class C
def self.classmethod
puts \"class method #{self}\"
end
end
Most of what happens in Ruby involves classes and modules, containing definitions of instance methods
class C
def talk
puts "Hi!"
end
end
c = C.new
c.talk
Output: Hi!
But as you saw earlier (even earlier than you saw instance methods inside classes), you can also define singleton methods directly on individual objects:
obj = Object.new
def obj.talk
puts "Hi!"
end
obj.talk
#Output: Hi!
When you define a singleton method on a given object, only that object can call that method. As you’ve seen, the most common type of singleton method is the class method—a method added to a Class object on an individual basis:
class Car
def self.makes
%w{ Honda Ford Toyota Chevrolet Volvo }
end
end
But any object can have singleton methods added to it. The ability to define method- driven behavior on a per-object basis is one of the hallmarks of Ruby’s design.
Singleton classes are anonymous: although they’re class objects (instances of the class Class ), they spring up automatically without being given a name. Nonetheless, you can open the class-definition body of a singleton class and add instance methods, class methods, and constants to it, as you would with a regular class.
Note:
Every object has two classes:
■ The class of which it’s an instance
■ Its singleton class
1: The Ruby Object Model and Metaprogramming For detail info about singleton method vs. class method ruby
2: MetaProgramming - Extending Ruby for Fun and Profit - by Dave Thomas
Hope this help you!!!