From: Avi Bryant Date: 2001-07-24T06:01:46+09:00 Subject: [ruby-talk:18386] Re: More newbie questions On Tue, 24 Jul 2001, Matt wrote: > On Tue, 24 Jul 2001, Dave Thomas wrote: > > Matt writes: > > > > > cgi.out { cgi.p { cgi.rfc1123_date (Time.now) } } > > > > rfc1123_date is a class method of CGI, as opposed to an instance > > method. This means you'd call it using > > > > CGI.rfc1123_date(Time.now) > > > > Here you're using the class (CGI) as the receiver of the message, as > > opposed to an instance of the class (cgi in your example). > > OK. That worked! Now I'm confused (again) when to use the class and > when to use an instance. For example take rfc1123_date. Why wasn't it > inherited by the instance? I admit to not knowing enough about OO, but > the only other language I've ever really tried was Perl's OO. And I > hated it. ;) Classes are themselves objects, and have a completely different set of methods from their instances. For example, CGI.new calls the "new" method on the CGI class object, which returns a new CGI instance. However, "new" is not defined for instances: cgi = CGI.new cgi2 = cgi.new #this doesn't work Class methods are often used for general utility functions that don't have to do with a particular instance - since it wouldn't matter *which* instance of cgi you called rfc1123_date on, it's made a class method instead. Class methods have other uses, too, of course. There are a number of ways to define class methods - the most common is probably this one: class Foo def bar #this is an instance method end def Foo.bar #this is a class method end end Class methods are actually a special case of Ruby's singleton methods; there's probably an index entry for that term in the pickaxe book, but I can't give you a page number right now. Cheers, Avi