How to create CSV from a text file in Ruby

csv, ruby

Solution

I think you've almost got it. Here's a simple way of doing it without regex:

string = '01.02.2016 10:35:49 8998775 New York 3:35 0,00 0,00'
data = string.split(' ')

data.shift(3)
# => ["01.02.2016", "10:35:49", "8998775"]

data.pop(3)
# => ["3:35", "0,00", "0,00"]

data.join(' ')
# => "New York"

# putting it together
first, third, second = data.shift(3), data.pop(3), [data.join(' ')]
csv << first + second + third

Something more compact, though a little harder to read:

data = call.split(' ')
csv << [data.shift(3), data.pop(3)].insert(1, data.join(' ')).flatten

Problem

I need to create a CSV file from a textfile with billing data about my calls. My textfile has a structure like: ``` 01.02.2016 10:35:49 8998775 New York 3:35 0,00 0,00 ``` I create the CSV using: ``` require 'csv' @calls = File.new("modified_billing", "r") CSV.open("new.csv", 'wb', write_headers: true, headers: ["Date", "Time", "Phone number","City","Duration", "Cost", "Cost of call"]) do |csv| @calls.each do |call| csv << call.split(" ") end end ``` It works for cities which have singular name, but obviously it doesn't for "New York", "Las Vegas", etc. because it creates two columns out of them.

Original source