From: Paul Lutus Date: 2006-08-31T01:55:29+09:00 Subject: Re: Parsing CSV file with ruby Drew Olson wrote: > Let me be more specific: essentially I want to find the groups of rows > that share an element. Let's say each row in my CVS doc has 3 elements. > I want to iterate across every group of rows that share the same value > for the first element. Hope this makes sense. > #!/usr/bin/ruby -w row_hash = {} File.open("data.txt").each { |record| fields = record.split(",") row_hash[fields.first] = [] unless row_hash[fields.first] row_hash[fields.first] << record } row_hash.keys.sort.each { |key| puts "Group: #{key}" row_hash[key].each { |record| puts "\t#{record}" } } data.txt: a,this,is,one,record a,this,is,another,record b,this,is,one,record b,this,is,another,record c,this,is,one,record c,this,is,another,record output: Group: a a,this,is,one,record a,this,is,another,record Group: b b,this,is,one,record b,this,is,another,record Group: c c,this,is,one,record c,this,is,another,record -- Paul Lutus http://www.arachnoid.com