From: Robert Klemme Date: 2006-02-03T19:23:18+09:00 Subject: Re: Seeking the Ruby way Todd Breiholz wrote: > I'm just getting my feet wet with Ruby and would like some advice on > how you "old-timers" would write the following script using Ruby > idioms. > > The intent of the script is to parse a CSV file that contains 2 > fields per row, sorted on the second field. There may be multiple > rows for field 2. I want to get a list of all of the unique values of > field2 that has more than 1 value for the 1st 6 characters of field 1. There are two possible interpretations of what you state here: 1. You want all values for row2 that occur more than once. 2. You want all values for row2 that have more than one distinct row1 value. Implementations: ad 1. require 'csv' h = Hash.new(0) CSV::Reader.parse(ARGF) {|row| h[row[1]] += 1} h.each {|k,v| puts k if v > 1} ad 2. require 'csv' require 'set' h = Hash.new {|h,k| h[k] = Set.new} CSV::Reader.parse(ARGF) {|row| h[row[1]] << row[0]} h.each {|k,v| puts k if v.size > 1} Note: CSV::Reader can use ARGF which makes it easy to read from stdin as well as multiple files. Kind regards robert