From: Leslie Viljoen Date: 2011-01-25T14:09:01+09:00 Subject: Re: Obtain data from .csv On Tue, Jan 25, 2011 at 3:22 PM, Kamarulnizam Rahim wrote: > Sample of .csv file: > > ["Issue,,Risk/Opportunity,Compliance,Consequence,Current Status,Due > Date,Priority,Responsibility,Probability"] > ["1,Efficiency (Energy),No > Action,Unknown,Neutral,Active,,Medium,,Possible"] > ["Action,,Cost,Status,Due Date,Responsibility,,,,"] > ["1.a,Maximise use of natural lighting,,Active,,,,,,"] > ["1.b,Turn-off unnecessary lights/equipment,,Active,,,,,,"] > ["1.c,Install energy efficient lighting,,Active,,,,,,"] > ["1.d,Turn-off unnecessary air conditioning,,Active,,,,,,"] > > Using the following code: > > f = File.open("ActionPlan.csv", "r") > f.each_line { |line| >  fields = line.split(',') >  #......... > } > > Anyone knows how to use ruby code to obtain the following data(question) > from the file? > > - Maximise use of natural lighting > - Turn-off unnecessary lights/equipment > > I only know how to obtain data from the first two lines using the > following code: > >  p.issue = fields[0].tr_s('"', '').strip >  p.blank = fields[1].tr_s('"', '').strip >  p.risk_opportunity = fields[2].tr_s('"', '').strip >  p.compliance = fields[3].tr_s('"', '').strip >  p.consequence = fields[4].tr_s('"', '').strip >  p.current_status = fields[5].tr_s('"', '').strip >  p.due_date = fields[6].tr_s('"', '').strip >  p.priority = fields[7].tr_s('"', '').strip >  p.responsibility = fields[8].tr_s('"', '').strip >  p.probability = fields[9].tr_s('"', '').strip > > But dont know how to obtain the rest of the data. Any help would be > great. Thanks in advance I'd use the fastercsv gem: \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ require 'fastercsv' FasterCSV.foreach('test.csv', :headers => true) do |row| puts row[nil] end \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ I am assuming each line doesn't really have square brackets and quotes around it, but if it does you can strip those off before passing the result to fastercsv. Some examples here: http://fastercsv.rubyforge.org Its great making your own CSV parser until you (inevitably) get some data with quotes in it and then it all goes downhill. Inside the loop there I am printing out the column without any name, which is the column you wanted. If you changed the first line of your CSV file to: Issue,Comment,Risk/Opportunity,Compliance,Consequence,Current Status,Due Date,Priority,Responsibility,Probability ..then you could change the: puts row[nil] to puts row["Comment"]