Last active
December 22, 2015 08:28
-
-
Save ezy023/6444824 to your computer and use it in GitHub Desktop.
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' | |
# ["id", "first_name", "last_name", "email", "phone", "created_at"] | |
class Person | |
attr_reader :first_name, :last_name, :email | |
def initialize(attributes) | |
@id = attributes["id"] | |
@first_name = attributes["first_name"] | |
@last_name = attributes["last_name"] | |
@email = attributes["email"] | |
@phone = attributes["phone"] | |
end | |
def to_a | |
[self.first_name, self.last_name, self.email] | |
end | |
# Look at the above CSV file | |
# What attributes should a Person object have? | |
end | |
class PersonParser | |
attr_reader :file | |
def initialize(file, save_file) | |
@file = file | |
@people = [] | |
@save_file = save_file | |
end | |
def people | |
return @people if @people | |
CSV.foreach(@file, {:headers => true}) do |row| | |
@people << Person.new(row) | |
end | |
end | |
def save_to_csv | |
CSV.open(@save_file, 'w') do |csv| | |
people.each do |person| | |
csv << person.to_a | |
end | |
end | |
end | |
end | |
parser = PersonParser.new('people.csv', 'erik_and_ted_and_crew.csv') | |
puts "There are #{parser.people.size} people in the file '#{parser.file}'." | |
parser.save_to_csv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment