2013-06-13 25 views
2

我想阅读一个csv行,更新一个字段,然后再用引号输出行。红宝石阅读和写入CSV与行情

Row Example Input => "Joe", "Blow", "[email protected]" 
Desired Row Example Output => "Joe", "Blow", "[email protected]" 

My script below outputs => Joe, Blow, [email protected] 

它丢失了我想保留的双引号。

我已经尝试过各种选择,但目前为止没有喜悦..任何提示?

非常感谢!

require 'csv' 

CSV.foreach('transactions.csv', 
      :quote_char=>'"', 
      :col_sep =>",", 
      :headers => true, 
      :header_converters => :symbol) do |row| 

row[:customer_email] = '[email protected]' 

puts row 

end 
+0

你想添加引号,如果有摆在首位有没有?或者你会一直有报价进来? –

+0

行情是在那里摆在首位。 –

回答

6

CSV字段中的引号通常是不必要的,除非字段本身包含分隔符或换行符。但是您可以强制CSV文件始终使用引号。 For that, you need to set force_quotes => true

CSV.foreach('transactions.csv', 
      :quote_char=>'"', 
      :col_sep =>",", 
      :headers => true, 
      :force_quotes => true, 
      :header_converters => :symbol) do |row| 
+0

:force_quotes => true对输出没有任何影响 –

+0

引号仅在写入新的CSV文件时相关,而不适用于屏幕上的输出。 –

0

您可以手动将它们添加到您的所有项目

Hash[row.map { |k,v| [k,"\"#{v}\""] }] 

(编辑,因为我忘了你有一个哈希值,而不是一个数组)

+0

靠近我感觉到但仍然没有快乐。这个输出像“[:customer_email,”[email protected]“]” –

+0

@ user1064314忘记了您正在使用散列;编辑它:) –

+0

添加行=散列[row.map {| k,v | [put,然后输出如下所示::customer_email =>“\”[email protected] \“” –

0

感谢贾斯汀L.

以您的解决方案为基础,并以此结束。

我感觉Ruby有一些更优雅,但这确实是我需要:

require 'csv' 

CSV.foreach('trans.csv', 
      :quote_char=>'"', 
      :col_sep =>",", 
      :headers => true, 
      :header_converters => :symbol) do |row| 

row[:customer_email] = '[email protected]' 

row = Hash[row.map { |k,v| [k,"\"#{v}\""] }] 

new_row = "" 

row.each_with_index do | (k, v) ,i| 
    new_row += v.to_s 
    if i != row.length - 1 
    new_row += ',' 
    end 
end 

puts new_row 

end