Phrogz
11/1/2007 3:20:00 AM
On Oct 31, 5:28 pm, Thufir <hawat.thu...@gmail.com> wrote:
> On Oct 31, 2:17 pm, 7stud -- <bbxx789_0...@yahoo.com> wrote:
> What would be a case where there's a SongList object, though? Or, if
> there are class methods then generally there won't be objects of that
> class?
class Rectangle
def self.all
@all ||= []
end
def initialize( width, length )
@width, @length = width, length
self.class.all << self
end
def self.square( length )
new( length, length
end
def self.double( width )
new( width, width * 2 )
end
end
r1 = Rectangle.new( 5, 7 )
r2 = Rectangle.square( 15 )
r3 = Rectangle.double( 6 )
p Rectangle.all
That's a very simple example of two common situations for me: using
class methods to report information about all instances of the class
(which I'm manually tracking here), and using class methods as
alternative constructors that return specialized instances.