spuder
spuder

Reputation: 18467

How would you replace the headers in a CSV file?

I'm brand new to ruby, and fairly new to programming.

How would you change the headers of a csv file?

foo, bar, foobar
1,   2,   3,
4,   5,   6,
7,   8,   9,

Change to:

herp, derp, herpaderp
1,    2,    3,
4,    5,    6,
7,    8,    9, 

I have found this question, however it doesn't really apply since I'm using the built in 'csv' library instead of the older 'fastcsv' library. (using ruby 2.0.0 on Mac OSX)

What I've tried.

require 'csv'
@filename = ARGV[0]
new_headers = ["herp", "derp", "herpaderp"]

origional_csv = CSV.read(@filename, {headers: true, return_headers: true })
headers = CSV.open(@filename, 'r', :headers => true).read.headers
puts headers

#Change headers to new_headers ? 

Calling test.rb from the command line with foo.csv file

$ ruby test.rb foo.csv
foo, bar, foobar

Upvotes: 0

Views: 244

Answers (1)

tadman
tadman

Reputation: 211720

You don't even need to do this with the CSV library. Just change the first line of the file, output the rest the same:

lines = File.readlines(@filename)
lines.shift
lines.unshift(["herp", "derp", "herpaderp"].join(',') + "\n")
puts lines.join('')

Upvotes: 1

Related Questions