Skip to content

Instantly share code, notes, and snippets.

@damncabbage
Created June 8, 2014 09:12
Show Gist options
  • Save damncabbage/c2585a8f5e8e785ea010 to your computer and use it in GitHub Desktop.
Save damncabbage/c2585a8f5e8e785ea010 to your computer and use it in GitHub Desktop.
Writing Object to CSV
require 'csv'
# A class and object of some sort.
# (Ignore the OpenStruct thing; I'm being lazy when I'm making my example objects.)
require 'ostruct'
class Car < OpenStruct(:name, :made_in)
end
cars = [
Car.new(name: "Shitbox Mazda", made_in: 1992),
Car.new(name: "Shiny Electric Thing", made_in: 2013),
]
### Actually doing the CSV thing ###
# Opening "cars.csv", in the current directory, for [w]riting:
CSV.open('./cars.csv', 'w') do |csv|
# For all the cars:
cars.each do |car|
# Add a new row, with these fields in order:
csv << [
car.name,
car.made_in,
]
end
end
require 'csv'
# A class and object of some sort.
class Car
attr_accessor :name, :made_in
end
object = Car.new
object.name = "Shitbox Mazda"
object.made_in = 1992
### Actually doing the CSV thing ###
# Opening "cars.csv", in the current directory, for [w]riting:
CSV.open('./cars.csv', 'w') do |csv|
# Add a new row, with these fields in order:
csv << [
object.name,
object.made_in,
]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment