Output array to CSV in Ruby
To a file:
require 'csv'
CSV.open("myfile.csv", "w") do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
# ...
end
To a string:
require 'csv'
csv_string = CSV.generate do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
# ...
end
Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html
convert array to CSV file on ruby
I managed to do this with(2nd edit) proper indentation
headers = ["user_id", "created_at"]
CSV.open("myfile.csv", "w", :col_sep => "\t| ", :headers => true) do |csv|
csv << headers
csv << ["-"*(headers.join.length+4*headers.length)] #Header separator in the length of header columns + tabs
a.each {|row| csv << row } #Adding rows for each element of a
end
Writing array into csv file
How about this? CSV creation outside the results loop.
require 'tiny_tds'
require 'csv'
db_host = 'myserver.com'
db_user = 'mylogin'
db_pass = 'mypassword'
client = TinyTds::Client.new(:host => db_host, :username => db_user, :password => db_pass)
results = client.execute("SELECT * FROM mydatabase")
CSV.open("data.csv", "wb") do |csv|
results.each do |row|
csv << row.to_a
end
end
Write an array to multi column CSV format using Ruby
Alternately using the CSV Class:
def write_to_csv(row)
if csv_exists?
CSV.open(@csv_name, 'a+') { |csv| csv << row }
else
# create and add headers if doesn't exist already
CSV.open(@csv_name, 'wb') do |csv|
csv << CSV_HEADER
csv << row
end
end
end
def csv_exists?
@exists ||= File.file?(@csv_name)
end
Call write_to_csv
with an array [col_1, col_2, col_3]
Wrapping output of an array to CSV conversion in quotations in Ruby
You can pass the :force_quotes
option to the CSV library to have it quote everything in the csv for you:
base_options = {headers: ['first,col', 'second column'], write_headers: true}
options = [{}, {force_quotes: true}]
data = [
['a', 'b'],
['c', 'd'],
['e', 'f']
]
options.each do |option|
result = CSV.generate(base_options.merge(option)) do |csv|
data.each do |datum|
csv << datum
end
end
puts "#{option}:\n#{result}"
end
For instance, in this small script, by default, the only thing that gets quoted is the first column header because it contains a comma. By passing in force_quotes: true
, in the second pass though, everything gets quoted.
Output:
{}:
"first,col",second column
a,b
c,d
e,f
{:force_quotes=>true}:
"first,col","second column"
"a","b"
"c","d"
"e","f"
Output many arrays to CSV-files in Ruby
You need to put the iteration inside the open CSV file:
CSV.open("#{foobar}_new.csv", "w") do |csv|
arr.each { |p|
csv << p.print_csv_record
}
end
Ruby 2d array to csv?
You are not writing to file.
require 'csv'
CSV.open('file.csv', 'w') do |csv|
arr1.each { |ar| csv << ar }
end
Related Topics
Rails: Activerecord Query Based on Association Value
Get Names of All Files from a Folder With Ruby
Strange \N in Base64 Encoded String in Ruby
Ruby 1.9 Array.To_S Behaves Differently
How to Check If a Value Exists in an Array in Ruby
Is There Any Difference Between the ':Key =≫ "Value"' and 'Key: "Value"' Hash Notations
How to Convert a String Object into a Hash Object
Ruby 1.9: Invalid Byte Sequence in Utf-8
Difference Between a Class and a Module
Converting a Nested Hash into a Flat Hash
How Does Instance_Eval Work and Why Does Dhh Hate It
How to Avoid Tripping Over Utf-8 Bom When Reading Files
How to Break Outer Cycle in Ruby
Using 'Return' in a Ruby Block
Rails 4: Before_Filter Vs. Before_Action
&:Views_Count' in 'Post.Published.Collect(&:Views_Count)'
Ruby 1.9: How to Properly Upcase & Downcase Multibyte Strings