From: Robert Klemme Date: 2007-12-13T00:43:16+09:00 Subject: Re: Creating multiple objects in loops 2007/12/12, Richard Harris : > Thanks for that but having looked at your solution, it may not be the > best idea. This is what I am trying to acomplish: > > Text File > ------------------------------------------------------------------------------ > ID: 1, entry1 # Can have multiple ID's > Name: Richard > Age: 20 > Address: 123 Some Road # Can have multiple lines of address, not > fixed > Address: Some City > Address: Some Country > ID: 2 > Name: Richard > Age: 20 > Address: 123 Some Road > Address: Some City > Address: Some Country > ID: 3 > Name: Richard > Age: 20 > Address: 123 Some Road > Address: Some City > Address: Some Country > ------------------------------------------------------------------------------- > > Parse the file and store the information so it can be printed out when > requested. So the info associated with ID: 1 is stored > together, info associated with ID: 2 is stored together etc. Then I will > have an array/hash of id's. The info associated with > these id's need to be printed, but I might only need id 1 and 2 so I > will have to search the stored info for the required id's. > > I have tried numerous ideas for this but some problem always arises > which stops me in my tracks. I have tried using hashes, objects etc but > as my knowledge of Ruby is limited I don't know all the tricks so it > might be very simple. > > Many thanks for any advice and if you can point me in the right > direction that would be great. Are ids always showing up in order without holes? If so, you can simply store them in arrays Entry = Struct.new :name, :age, :addresses do def initialize() self.addresses = [] end end data = [] io.each do |line| line.chomp! case line when /^ID/ data << Entry.new when /^Name:\s*(\S+)/ data.last.name = $1 ... end end Cheers robert -- use.inject do |as, often| as.you_can - without end