Ruby 如何替换CSV头文件

Ruby 如何替换CSV头文件,ruby,csv,Ruby,Csv,如果在ruby中使用“csv”库,如何在不重新读取文件的情况下替换标题 foo.csv 'date','foo',bar' 1,2,3 4,5,6 使用CSV::表 这是一个可行的解决方案,但是它需要从文件中写入和读取两次 require 'csv' @csv = CSV.table('foo.csv') # Perform additional operations, like remove specific pieces of information. # Save fixed cs

如果在ruby中使用“csv”库,如何在不重新读取文件的情况下替换标题

foo.csv

'date','foo',bar'
1,2,3
4,5,6
使用CSV::表

这是一个可行的解决方案,但是它需要从文件中写入和读取两次

require 'csv'
@csv = CSV.table('foo.csv')

# Perform additional operations, like remove specific pieces of information. 

# Save fixed csv to a file (with incorrect headers)
File.open('bar.csv','w') do |f|
  f.write(@csv.to_csv)
end

# New headers
new_keywords = ['dur','hur', 'whur']

# Reopen the file, replace the headers, and print it out for debugging
# Not sure how to replace the headers of a CSV::Table object, however I *can* replace the headers of an array of arrays (hence the file.open)
lines = File.readlines('bar.csv')
lines.shift
lines.unshift(new_keywords.join(',') + "\n")
puts lines.join('')

# TODO: re-save file to disk
如何在不从磁盘读取两次的情况下修改标题

'dur','hur','whur'
1,x,3
4,5,x
更新
对于那些好奇的人。为了使用诸如
delete\u if()
之类的功能,必须使用CSV.table()函数导入CSV


也许可以通过将csv表转换为数组来更改标题,但是我不知道如何做到这一点

给定一个
test.csv
文件,其内容如下所示:

id,name,age
1,jack,8
2,jill,9
您可以使用以下方法替换标题行:

require 'csv'

array_of_arrays = CSV.read('test.csv')

p array_of_arrays # => [["id", "name", "age"],
                  # =>  ["1", "jack", "26"],
                  # =>  ["2", "jill", "27"]]    

new_keywords = ['dur','hur','whur']

array_of_arrays[0] = new_keywords

p array_of_arrays # => [["dur", "hur", "whur"],
                  # =>  ["1", " jack", " 26"],
                  # =>  ["2", " jill", " 27"]]
或者,如果您希望保留原始二维数组:

new_array = Array.new(array_of_arrays)
new_array[0] = new_keywords

p new_array # => [["dur", "hur", "whur"],
            # =>  ["1", " jack", " 26"],
            # =>  ["2", " jill", " 27"]]

p array_of_arrays # => [["id", "name", "age"],
                  # =>  ["1", "jack", "26"],
                  # =>  ["2", "jill", "27"]]

在您的示例中,您正在读取一个csv,向另一个csv写入,再次读取第二个csv,并最终将其全部打印为字符串。您是否希望完全相同的内容只包含不同的标题?所需的输出是最后一个代码段吗?我添加了一些代码注释,可以更好地说明这一点。我试图在一个不那么笨重的庄园里用“dur”、“hur”、“whur”替换“date”、“foo”、“bar”。为什么不在文件的初始读取中,用
headers:true
跳过标题,然后在新的csv中写下您想要的标题?我正在csv表上执行一些操作,需要知道标题是什么。谢谢,但是,代码已经在使用CSV.table(),因此头被创建为一个符号,从而允许使用delete_if()。这可以通过CSV.table()完成吗