From: Logan Capaldo Date: 2006-05-07T05:23:11+09:00 Subject: Re: self.new and initialize ( was Re: Creating sub-classes using Struct) On May 6, 2006, at 4:10 PM, Bira wrote: > On 5/6/06, Logan Capaldo wrote: > >> I would suggest >> >> class Database >> def self.new(file_containing_info) >> fields = parse_field_format(file_containing_info) >> Database.const_set('Record", Struct.new(*fields)) >> super >> end >> >> def initialize(file) >> @records = [] >> read_each_record_in_file(file) do |record_data| >> record = Database::Record.new >> extract_record_data_into(record_data, record) >> @records << record >> end >> end >> end > > I think I still have a long way to go before I can write a decent, > Ruby-ish example :). This one is a little beyond my ability to > understand at a glance... > > What happens when I call Database.new(some_file) ? In which order to > the "new" and "initialize" methods get called? > Basically new calls initialize, and then returns the instance of the object. The normal implementation of new would look something like: class Class def new(*args, &block) obj = self.allocate obj.initialize(*args, &block) obj end end My new does some extra work by defining the Record class based on some info in the file. There's a big problem with my code though and it's called Only one database per program!. Or at least only one at a time e.g. db1 = Database.new(file1) db2 = Database.new(file2) if file2 has a different record format than file1, it's going to seriously mess up any interactions with db1. An alternative method would be of course to do something like class Database def initialize(file) @Record = Struct.new(...) ... end end > -- > Bira > http://compexplicita.blogspot.com > http://sinfoniaferida.blogspot.com >