Thursday, March 15, 2007

Instance Method V.S. Singleton Method

Just keep in mind that methods written inside a class, for the benefit of all of that class’s instances, are instance methods, whereas a method defined for a specific object (def ticket.event) is a singleton method of that object.)

Nothing stops you from defining a method twice, or overriding it:
class C
      def m
            puts "First definition of method m"
      end
      def m
            puts "Second definition of method m"
      end
end
What happens when we call m on an instance of C? Let’s find out:
C.new.m
The printed result is Second definition of method m.

Most Ruby programmers are conservative. You’ll see less adding of methods to individual objects than you might expect. Methods are most often added to Class objects; those methods are class methods, which are a good design fit in many cases.

No comments: