Class, Instance and Singleton methods

December 20, 2007

Ruby has three kinds of methods, and I always mix up the terminology. So here, mostly for my own future reference, is a quick rundown of each. #### Class methods These are methods you call directly on the class itself. No instance required. ```ruby Time.now Monkey.find(:all) ``` #### Instance methods These are methods available on *any* instance of a class. Every object of that type gets them. ```ruby @widget.to_s Time.now.to_f ``` #### Singleton methods These are methods defined on one *specific* object. No other instance of that class will have them -- they belong to that particular object alone. ```ruby chicken = Chicken.new class << chicken def hide # ... end end chicken.hide ``` Here, only this particular `chicken` can `hide`. Create another `Chicken.new` and it won't know what you're talking about. The key distinction is scope: class methods live on the class, instance methods live on every object of that class, and singleton methods live on exactly one object. Once you internalise that, it all clicks into place.
Questions or thoughts? Get in touch.