Created
June 8, 2014 09:12
-
-
Save damncabbage/c2585a8f5e8e785ea010 to your computer and use it in GitHub Desktop.
Writing Object to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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