From: ara.t.howard@... Date: 2006-02-03T07:21:56+09:00 Subject: Re: Seeking the Ruby way On Fri, 3 Feb 2006, 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. > > Here's what I did: > > require 'csv' > > last_account_id = '' > last_adv_id = '' > parent_co_ids = [] > cntr = 0 > first = true > CSV::Reader.parse(File.open('e:\\tmp\\20060201\\bsa.csv', 'r')) do |row| > if row[1] == last_account_id > parent_co_ids << last_adv_id[0, 6] unless > parent_co_ids.include?(last_adv_id[0, 6]) > else > if !first > parent_co_ids << last_adv_id[0, 6] unless > parent_co_ids.include?(last_adv_id[0, 6]) > if parent_co_ids.size > 1 > puts "#{last_account_id} - (#{parent_co_ids.join(',')})" > cntr = cntr + 1 > end > parent_co_ids.clear > else > first = false > end > end > last_account_id = row[1] > last_adv_id = row[0] > end > puts "Found #{cntr} accounts with multiple parent companies" > > Thanks in advance! > > Todd Breiholz harp:~ > cat a.rb require "csv" require "yaml" path = ARGV.shift sum = Hash::new{|h,k| h[k] = 0} count = lambda{|row| sum[row.last.to_s[0,6]] += 1} CSV::open(path,"r"){|row| count[row]} y sum.delete_if{|k,v| v == 1} harp:~ > cat in.csv 0,aaaaaa___ 1,aaaaaa___ 2,aaabbb___ 3,aaabbb___ 4,aaabbb___ 5,aaaccc___ harp:~ > ruby a.rb in.csv --- aaaaaa: 2 aaabbb: 3 hth. regards. -a -- happiness is not something ready-made. it comes from your own actions. - h.h. the 14th dali lama