Search code examples
rubyfilecsvfwrite

Issue with writing data into an existing CSV file using ruby


test1.csv

yearID,teamID,lgID,playerID,salary
1985,BAL,AL,boddimi01,625000
1985,BAL,AL,dauerri01,480000
1985,BAL,AL,davisst02,437500
1986,BAL,AL,dempsri01,512500
1986,BAL,AL,dwyerji01,375000
1987,BAL,AL,flanami01,641667

This is my ruby code!

File.foreach('test1.csv') do |csv_line|
    row = CSV.parse_line(csv_line)
    
    if File.exist?("year_#{row[0]}_info.csv")
        File.open("year_#{row[0]}_info.csv", 'w') do |f|     
            f.write("\n#{row[4]}")   
        end
    else
        File.open("year_#{row[0]}_info.csv", 'w') do |f|     
            f.write("#{row[4]}")   
        end
    end
end

I am trying to get one of the following output

#year_1985_info.csv
625000
480000
437500

But I am only getting this output

#year_1985_info.csv

437500

How do I get the desired output?

Thanks a lot in advance!


Solution

  • It's inefficient to keep opening and closing the same file.

    What I would do is group them by year and then print them to each file all at once.

    scores = CSV.read('test1.csv').drop(1) #drop header line
    grouped = scores.group_by(&:first)     #group by year
    
    grouped.each do |year, rows|
      File.open("year_#{year}_info.csv", "w") do |f|
        f.puts rows.map(&:last)  #just want last column
      end
    end