如何向特定列添加一行数据?

时间:2016-04-29 22:36:25

标签: ruby csv

我有一个名为test.csv的CSV,其标题如下所示:

"Fruit","Weight","Color"

在我的ruby脚本中,我有一个如下所示的数组:

["Banana","Yellow"]

如何使用Ruby的csv类将"Banana"放在列"Fruit""Yellow"列中的"Color"

1 个答案:

答案 0 :(得分:3)

对于你的例子:

CSV.open("path/to/file.csv", "wb") do |csv|
  fruit, color = ["Banana","Yellow"]
  csv << [fruit, nil, color]
end

如果您有多个具有相同结构的行:

CSV.open("path/to/file.csv", "wb") do |csv|
  rows.each do |row|
    # Assuming row looks like ["Banana", "Yellow"]
    fruit, color = row
    csv << [fruit, nil, color]
  end
end

如果在您的现实生活示例中,您的数组有更多列(而不仅仅是两个),并且您希望偶尔添加一些空列,则可以使用Array#insert方法:

CSV.open("path/to/file.csv", "wb") do |csv|
  rows.each do |row|
    # Run one line like this for every empty column you want to add
    # Note that it changes the value of `row`, so if you'd like to 
    # keep it untouched, consider using `dup`
    row.insert(1, nil)
    csv << row
  end
end