From: 7stud -- Date: 2008-01-23T10:48:58+09:00 Subject: Re: How to improve this code? 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. > > Basically the CSV looks like this: > bla@bla.com,value1 > bla@bla.com,value2 > bla@bla.com,value3 > bla@bla.com,value4 > ruby@ruby.br,value1 > ruby@ruby.br,value2 > > the output should be in two lines > bla@bla.com,value1,value2,value3,value4 > ruby@ruby.br,value1,value > > 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. > > The code following below: > > h = Hash.new > File.open("Sector_brand.csv").each_line do |lines| > values = lines.split(",") > email = values[0] > content = values[1] > if h.key?(email) > l = h[email] > l.push content > h[email] = l > else > l = [content] > h[email] = l > end > end > > I didn't put the code to print the Hash. Also I didn't create the code > above in a class because it is just a test. > > Well guys, does anyone could see my code and give comments? How the code > above could be improved? > > Thanks in advice. > > Junior Try this: h = Hash.new do |hash, key| hash[key] = [] end IO.foreach('data.txt') do |line| data = line.chomp.split(',') h[data[0]] << data[1] end p h --output:-- {"ruby@ruby.br"=>["value1", "value2"], "bla@bla.com"=>["value1", "value2", "value3", "value4"]} -- Posted via http://www.ruby-forum.com/.