From: roktas Date: 2002-02-24T17:43:00+09:00 Subject: Re: Newbie question Hi, * David Alan Black [020224 10:12]: > Hello -- > > > Well... (1) I don't want to use any global var ($labels), (2) Seperating > > 'records' and 'whole database' (DB) would be fine. > > I'm not sure about (2). Somehow the Record has to know about the > fields in the database. Here's one way to do it with relatively > little overhead -- each Record has an instance variable which points > to the relevant fields array (but doesn't duplicate that array). > > > class TSDB < Array > attr_reader :labels, :records > SEP = "\t" > > def TSDB.parse_line(line, sep=SEP) > line.chomp.strip.split(/#{sep}/) > end > > class Record < Array > attr_accessor :fields > > def initialize(line) > concat(TSDB.parse_line(line)) > end > > def [](key) > at(@fields.index(key)) > end > end > > def initialize(f) > fh = File.open(f, "r") > @fields = TSDB.parse_line(fh.readline) > push("Dummy 0th record") > concat (fh.readlines.map do |line| > r = Record.new(line) > r.fields = @fields > r > end) > end > end > > # Based on same tsd.txt file as last time: > t = TSDB.new("tsd.txt") > p t[1]["field1"] # "one" > p t[2]["field2"] # "orange" > > This seems pretty good. I haven't even know of the nested class definition (which is the key point in your suggestion). Himm... I should read more documents. Thanks, regards. -- roktas