Rob V Rob V - 6 months ago 15
Ruby Question

Ruby split concatenated array element into separate array row and export to CSV

I am trying to split a concatenated field from a CSV and add it to a new row in Ruby. Here is an example of the data and desired output.

Sample Data

Year Make Model
1999 Chevy Camaro; Corvette; Cruz
2001 Ford Mustang; Shelby; SHO


Desired Output

Year Make Model
1999 Chevy Camaro
1999 Chevy Corvette
1999 Chevy Cruz
2001 Ford Mustang
2001 Ford Shelby
2001 Ford SHO


My main issue seems to come from the CSV.foreach method which turns each csv row of data into a separate array. If I try to split the array I cannot seem to get it to create a new row as it reads the csv data line by line. Any help would be greatly appreciated.

Answer

What about that ?

require 'csv'

desired_array = []

CSV.foreach('myfile.csv', :headers => true) do |csv_obj|
  csv_obj["Model"].split(/;\s*/).each do |model|
    new_row = [csv_obj["Year"], csv_obj["Make"], model]
    desired_array.push(new_row)
  end
end

p desired_array

Which gives the following array :

[
  ["1999", "Chevy", "Camaro"], 
  ["1999", "Chevy", "Corvette"], 
  ["1999", "Chevy", "Cruz"], 
  ["2001", "Ford", "Mustang"], 
  ["2001", "Ford", "Shelby"], 
  ["2001", "Ford", "SHO"]
]