From: Hunt Hunt Date: 2009-07-24T13:30:09+09:00 Subject: Re: splitting............. hi Glenn Let us suppose, an information.txt has following data --------------------------------------------------------- name,rollno,city,country ABC,123,NewYork,US XYZ,124,Pittsburg,US LMN,125,Moscow,RUSSIA ---------------------------------------------------------- Now how can i have name ABC,XYZ & LMN with name. 123,124,125 with rollno NewYork, Pittsburg, Moscow with city US, US, Russia with country. --------------------------------------------------------------- Glenn Jackman wrote: > At 2009-07-23 08:06AM, "Hunt Hunt" wrote: >> >> Now I have to split name, address,city & contact with their associated >> values. >> >> how am i supposed to do this? > > What do you want the resulting data structure to look like? > > This creates an array of hashes, and then a hash of arrays: > > filename = 'information.txt' > f = File.open(filename) > fields = f.gets.chomp.split(/,/) > data = [] > while line = f.gets > line.chomp! > data << Hash[fields.zip(line.split(/,/))] > end > p data > > f.rewind > fields = f.gets.chomp.split(/,/) > data = Hash.new([]) > while line = f.gets > line.chomp.split(/,/).each_with_index do |item, idx| > data[fields[idx]] += [item] > end > end > p data > f.close > > Or, take Robert Schaaf's advice and parse the file with CSV if you don't > control how it's created: > > require 'csv' > > csv = CSV.open(filename, 'r') > fields = csv.shift > data = [] > # assume no empty lines in the file > until (row = csv.shift).empty? > data << Hash[fields.zip(row)] > end > csv.close > p data -- Posted via http://www.ruby-forum.com/.