Rob V
Rob V

Reputation: 13

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.

Upvotes: 1

Views: 150

Answers (1)

Pholochtairze
Pholochtairze

Reputation: 1854

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"]
]

Upvotes: 1

Related Questions