From: Glenn Jackman Date: 2009-07-24T00:25:27+09:00 Subject: Re: splitting............. At 2009-07-23 08:06AM, "Hunt Hunt" wrote: > Hi Friends, > > I have a file which information.txt which is like > > name,address,city,contact > abc,Newyork,HYU,345 > xyz,Pittsurg,UYY,234 > > > only theree line. > > 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 -- Glenn Jackman Write a wise saying and your name will live forever. -- Anonymous