From: John Carter Date: 2008-01-23T11:36:46+09:00 Subject: Re: How to improve this code? On Wed, 23 Jan 2008, Jair Rillo Junior wrote: > Hi guys, > I am new in the Ruby world, I am coming from Java, and I would like to > "think " in Ruby instead Java. > > I did a code to read a CSV file (separated by comma), organize the > values and print the output. Probably the mostly useful first thought in Ruby is... "Nah, I bet it's in the standard library somewhere, better check ruby-doc.org" From standard library module 'csv' # Open a CSV formatted file for reading or writing. # # For reading. # # EXAMPLE 1 # CSV.open('csvfile.csv', 'r') do |row| # p row # end # # EXAMPLE 2 # reader = CSV.open('csvfile.csv', 'r') # row1 = reader.shift # row2 = reader.shift # if row2.empty? # p 'row2 not find.' # end # reader.close # # ARGS # filename: filename to parse. # col_sep: Column separator. ?, by default. If you want to separate # fields with semicolon, give ?; here. # row_sep: Row separator. nil by default. nil means "\r\n or \n". If you # want to separate records with \r, give ?\r here. # # RETURNS # reader instance. To get parse result, see CSV::Reader#each. # # # For writing. # # EXAMPLE 1 # CSV.open('csvfile.csv', 'w') do |writer| # writer << ['r1c1', 'r1c2'] # writer << ['r2c1', 'r2c2'] # writer << [nil, nil] # end # # EXAMPLE 2 # writer = CSV.open('csvfile.csv', 'w') # writer << ['r1c1', 'r1c2'] << ['r2c1', 'r2c2'] << [nil, nil] # writer.close # # ARGS # filename: filename to generate. # col_sep: Column separator. ?, by default. If you want to separate # fields with semicolon, give ?; here. # row_sep: Row separator. nil by default. nil means "\r\n or \n". If you # want to separate records with \r, give ?\r here. # # RETURNS # writer instance. See CSV::Writer#<< and CSV::Writer#add_row to know how # to generate CSV string. # > My initial thought was store the values into a Hash object, where the > KEY is the email (column a) and the value is an Array containing the > values (column b). > Going through all lines, test if the email address already exists in the > Hash, if so update the Array, otherwise create a new entry into the > Hash. My flavourite idiom is... require 'set' h = Hash.new{|hash,key| hash[key] = Set.new} then in the loop.. values = lines.split(",") email = values.shift h[email].merge(values) Ooh... That's just sooo pretty! John Carter Phone : (64)(3) 358 6639 Tait Electronics Fax : (64)(3) 359 4632 PO Box 1645 Christchurch Email : john.carter@tait.co.nz New Zealand