How to skip headings when writing CSV?

I am writing a CSV file, and CSV.dump displays two header lines that I do not need.

I tried to set :write_headers => false , but still it prints the title:

 irb> A = Struct.new(:a, :b) => A irb> a = A.new(1,2) => #<struct A a=1, b=2> irb> require 'csv' => true irb> puts CSV.dump [a], '', :write_headers => false, :headers=>false class,A a=,b= 1,2 
+4
source share
2 answers

I do not think you can do this with parameter parameters. But you can easily do what you want without using the generate method

 irb> arr = [a, a] => [#<struct A a=1, b=2>, #<struct A a=1, b=2>] irb> csv_string = CSV.generate do |csv| irb* arr.each {|a| csv << a} irb> end irb> puts csv_string 1,2 1,2 => nil 
+1
source

I think the problem is twofold:

 CSV.dump [a] 

wraps an instance of struct a in an array, which then CSV tries to sort. Although this can sometimes be useful when you try to create a CSV file for consumption by some other non-Ruby application that recognizes CSV, you will get values ​​that cannot be used. Looking at the output, this is not a CSV:

  class, A
 a =, b =
 1,2

Look at it in the IRB:

 => "class,A\na=,b=\n1,2\n" 

which, again, will not be accepted by something like a spreadsheet or database. So, another tactic is needed.

Removing an array from a does not help:

 CSV.dump a => "class,Fixnum\n\n\n\n" 

Going off in another way, I looked at the standard way to generate CSV from an array:

 puts a.to_a.to_csv => 1,2 

An alternative way to create it:

 CSV.generate do |csv| csv << a.to_a end => "1,2\n" 
0
source

All Articles