Need to quickly export a collection as a CSV? Ruby has an awesome class just for this (named CSV of course). With this class you can quickly output a csv string which can then be imported into Excel, Libre Office, etc.

Here's a quick example that is displaying some user information. **Note**: the last line is important for displaying the csv string without the \n character.

users = User.all
headers = ["Name", "Email", "Role"]

csv = CSV.generate do |csv|
  csv << headers # Add the headers to the csv

  users.each do |user|
    csv << [user.name, user.email, user.role]
  end
end

puts csv # output the csv string

Now just copy paste the string from your console into a new spreadsheet and it should properly delineate the columns and data. Easy!

« Previous Post
Custom Named Belongs_to Associations in Rails with foreign key constraints
Next Post »
What It Means to Stub the System Under Test

Join the conversation

comments powered by Disqus