3

这可行,但由于某种原因缺少逗号。data被插入为

GAURISH SHARMA
97
69
69
975
PASS

每个值都写在新行中。我想知道逗号去哪儿了?还是必须手动插入?


我正在尝试使用以下代码编写哈希值

CSV.open("resultdata.csv", "a") do |csv|    
  h.each do |key, value|
    csv << value
  end
end

这是h哈希的内容

{:name=>"GAURISH SHARMA",
 :ca=>"97",
 :cb=>"69",
 :ba_lab=>"69",
 :bb_lab=>"69",
 :grand_total=>"975",
 :result=>"PASS"}

此代码看起来正确,但在运行此代码时,会生成以下错误:

/home/gaurish/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/csv.rb:1729:in `<<': undefined method `map' for "GAURISH SHARMA":String (NoMethodError)
    from /home/gaurish/Dropbox/code/projects/ra/result.rb:35:in `block (2 levels) in <main>'
    from /home/gaurish/Dropbox/code/projects/ra/result.rb:34:in `each'
    from /home/gaurish/Dropbox/code/projects/ra/result.rb:34:in `block in <main>'
    from /home/gaurish/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/csv.rb:1354:in `open'
    from /home/gaurish/Dropbox/code/projects/ra/result.rb:33:in `<main>'

知道这里有什么问题吗?

4

3 回答 3

11

When you do csv << value, you are writing a string to a file. The CSV library makes it possible to write an array to a file (in a certain form). The best way to get an array with all values from a hash is to use the values method btw. So:

require 'csv'
h = {:name=>"GAURISH SHARMA",
 :ca=>"97",
 :cb=>"69",
 :ba_lab=>"69",
 :bb_lab=>"69",
 :grand_total=>"975",
 :result=>"PASS"}

CSV.open("resultdata.csv", "a") do |csv|    
  csv << h.values
end

resultdata.csv will look like

GAURISH SHARMA,97,69,69,69,975,PASS
于 2012-07-04T20:21:59.483 回答
10

放入value一个数组中,如下所示:

CSV.open("resultdata.csv", "a") do |csv|    
  h.each do |key, value|
    csv << [value]
  end
end

已编辑

每次使用csv << ["foo"]它都会在新行中插入“foo”。但是如果你这样做csv << ["foo", "foo", "foo"],你会在同一行中得到 3 个“foo”,用逗号分隔。

Knowing this, try to store all the values inside an array first, and after this use the csv << your_values_array. This will solve your problem.

于 2012-07-04T18:42:53.800 回答
2

What csv << value is trying to do is append (<<) a new row onto the CSV. As such, it's expecting value to be an Array, not a String, with each element in the Array corresponding to a column/field of the row being appended. Thus, the following should work:

CSV.open("resultdata.csv", "a") do |csv|    
  h.each do |key, value|
    csv << [value]
  end
end
于 2012-07-04T18:43:04.640 回答