From: Dash Riprock Date: 2001-12-30T14:18:01+09:00 Subject: [ruby-talk:29704] Re: comma-delimited to an array nobu.nokada@softhome.net wrote: > At Sun, 30 Dec 2001 08:37:31 +0900, > Dash Riprock wrote: > > I've got a file in which each line has comma-delimited items. A > > sample might look like this: > > > > num,date,time,orig,type,action,rule,iface > > 1,28Dec2001,23:59:51,121.210.49.22,log,accept,16,eth-s1p2c0 > > 2,28Dec2001,23:59:44,121.210.48.11,log,drop,20,eth-s1p1c0 > > 3,28Dec2001,23:59:57,121.210.49.22,log,accept,16,eth-s1p1c0 > > > > Because the order of the items may *vary* from day to day, I want to > > treat each line as an array. > > Possibly, you may want to access each elements by names in the > first line? > > data = [] > open(file) do |f| > foo = Struct.new(nil, *f.gets.chomp.split(",")) > f.each do |line| > bar = foo.new(*line.chomp.split(",")) > data[bar.num.to_i] = bar > end > end > > p data[1].date # => "28Dec2001" > p data[2].action # => "drop" > p data[3].iface # => "eth-s1p1c0" The "line.chomp.split" idiom, which several people were kind enough to point out, was what I was looking for. But the above material by Nobu Nokada goes beyond that to a kind of mind reading. Thanks a lot!