1

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.

1
  • You need a CSV reader and writer. Do you have both of those? If so, it's a case of writing multiple lines for each input line. Commented May 11, 2016 at 16:12

1 Answer 1

1

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"]
]
Sign up to request clarification or add additional context in comments.

3 Comments

split("; ") or split(/;\s*/) would probably be better.
@Jordan You're right! I think your second option is cleverer (to match multiple spaces) so I'll take that one.
@ Jordan, that is perfect. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.