A quick note on how to export an Array of Objects to CSV in Ruby.
For example when fetching data in Rails with raw SQL via:
data = ActiveRecord::Base.connection.execute('SELECT ...').to_a
One will get following data structure:
puts data
{"id"=>1, "first_name"=>"John", "last_name"=>"Doe"}
{"id"=>2, "first_name"=>"Jane", "last_name"=>"Doe"}
{"id"=>3, "first_name"=>"Michal", "last_name"=>"Bryxí"}
Then this one-liner can be used to create a file called export.csv
with all the data:
File.write('./export.csv', data.map{
|row| row.values.to_csv
}.join)
Which will produce following output:
1,John,Doe
2,Jane,Doe
3,Michal,Bryxí
Image created with Midjourney prompt: Clerk looking at tables and writting stuff with a pencil on a paper; Ruby is shining on a shelf --ar 16:9
Top comments (0)