Export data to CSV in Ruby
Michal Bryxí

Michal Bryxí @michalbryxi

About: Cycle 🚴 , climb 🗻 , run 🏃 , travel 🌍 , enjoy life ♥. IT guy with the need to live fully.

Location:
Interlaken, Switzerland
Joined:
Feb 1, 2018

Export data to CSV in Ruby

Publish Date: Feb 27 '23
2 0

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
Enter fullscreen mode Exit fullscreen mode

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í"}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Which will produce following output:

1,John,Doe
2,Jane,Doe
3,Michal,Bryxí
Enter fullscreen mode Exit fullscreen mode

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

Comments 0 total

    Add comment