From: Richard Turner Date: 2005-01-21T23:58:55+09:00 Subject: Re: Refernce objects On Fri, 2005-01-21 at 23:36 +0900, David A. Black wrote: > > > > I'm new to Ruby > > Welcome! > Thank you :) > > At the risk of over-simplifying, let me try to simplify :-) > > Generally in Ruby you don't need or see too many methods with 'get' > and 'set' in their names, since there are a variety of ways to perform > those operations less verbosely. For example, you can define a method > called [] and then use index-style bracket syntax: > > class Section > def self.[](n) > # here, a fetch command for record n > end > end > > record = Section[10] > > That would bypass the need for a constructor (if that's appropriate in > your case). > That's great, but isn't that just a more succinct way of doing the same thing? I.e. isn't this the same?: class Section def self.loadedFromDB(sectionID) # here, a fetch command for record sectionID end end What I want []() or loadedFromDB() to return is a Section, but I don't want people to be able to call Section.new in error, otherwise they'll not get what they think. E.g.: secFromFactory1 = Section.getSection(10) => # secFromFactory2 = SectionFactory.getSection(10) => # BUT: secFromNew = Section.new(10) => # See the object IDs are the same from the factory but different using the constructor. So if I do: secFromFactory1.index = 2 secFromFactory2.index => 2 BUT: secFromNew.index => 1 In short, I've rather painfully created a factory method that, given an ID, returns the correct object from a pre-filled set. However, I now need to stop people using Section.new and I can't. This leads me to believe that there may be a Better Way, but I don't know what it is :( Cheers, Richard.