From: David Alan Black Date: 2002-02-24T07:01:25+09:00 Subject: Re: Newbie question Hello -- On Sun, 24 Feb 2002, roktas wrote: > Hi all, > > How can I create an array of array with some funny (!) properties? To > make clear, here is the exact problem: I have a tab seperated text file > which the first line points to the field labels, that is; > > field1\tfield2\tfield3 > foo\tbar\tgoo > .. > > I have created a 'DB' class which holds the whole data (after some > parsing). What I want to realize is something that results with the > following simple calls in the main block: > > db = DB.new("file.txt") > p db[3]["field2"] > > I have some experimental codes but don't include them to prevent messing > around. Inside a 'Record' class (inherited from Array), I have played > with [] method to take a string argument (like "field2" as shown above) > and used this class as the line container in a base array, but can't > succeed :( What you want, I think, is an array of hashes. Each hash would represent one line from your data file. Here's a little example, data file first then program file. It first grabs the first line from the file, and gets the field names from it. Then it reads the other lines; for each one, it creates a hash (with the field names as keys and the values from the line as values), and pushes that hash onto the TSDB object itself. # tsd.txt (tab-separated): field1 field2 field3 one two three apple orange banana # tsd.rb: class TSDB < Array def initialize(file) concat ["Dummy 0'th element"] # so that you can index from 1 fh = File.open(file, "r") fields = fh.readline.chomp.split(/\t/) fh.readlines.each do |line| data = line.chomp.split(/\t/) record = {} fields.each_with_index {|f,i| record[f] = data[i]} push(record) end end end t = TSDB.new("tsd.txt") p t[1]["field1"] # => "one" p t[2]["field2"] # => "orange" __END__ Since t[1] is a hash, you can get at its values with strings (i.e., its keys are strings). David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav