Skip to content

Instantly share code, notes, and snippets.

@jrgifford
Created April 10, 2019 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrgifford/b0cad6338f1e7dc3d99b1e551d32ccd6 to your computer and use it in GitHub Desktop.
Save jrgifford/b0cad6338f1e7dc3d99b1e551d32ccd6 to your computer and use it in GitHub Desktop.
Ruby CSV library is smart and will select just keys in the headers if given headers and a hash
require 'csv'
filename = "/tmp/csv_test.csv"
things_to_write = [
{a: "a", b: "b", c: "c"},
{c: "c", b: "b", a: "a", does_not: "exist"},
{a: "a", c: "c"}
]
CSV.open(filename, "wb", headers: things_to_write.first.keys) do |csv|
things_to_write.each do |thing|
csv << thing
end
end
`cat #{filename}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment