Created
October 28, 2013 06:50
-
-
Save zezantam/7192357 to your computer and use it in GitHub Desktop.
CSV In and Out exercise
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' | |
require 'date' | |
class Person | |
attr_reader :first_name, :last_name, :email, :phone, :created_at | |
def initialize(id, first_name, last_name, email, phone, created_at) | |
@id = id | |
@first_name = first_name | |
@last_name = last_name | |
@email = email | |
@phone = phone | |
@created_at = created_at | |
end | |
end | |
class PersonParser | |
attr_reader :file | |
def initialize(file) | |
@file = file | |
@people = nil | |
end | |
def people | |
require 'csv' | |
@people = [] | |
CSV.foreach(@file) do |row| | |
@people << row | |
end | |
return @people if @people != nil | |
end | |
def add_person(person) | |
new_person = [] | |
new_person << (@people.last[0].to_i+1).to_s | |
new_person << person.first_name | |
new_person << person.last_name | |
new_person << person.email | |
new_person << person.phone | |
new_person << person.created_at | |
@people << new_person | |
puts "#{person.first_name} #{person.last_name} has been added" | |
return @people if @people != nil | |
end | |
# If we've already parsed the CSV file, don't parse it again. | |
# Remember: @people is +nil+ by default. | |
# We've never called people before, now parse the CSV file | |
# and return an Array of Person objects here. Save the | |
# Array in the @people instance variable. | |
def save(file) | |
require 'csv' | |
CSV.open(file, "wb") do |csv| | |
@people.each {|a| | |
csv << a | |
} | |
end | |
end | |
end | |
parser = PersonParser.new("people.csv") | |
puts "There are #{parser.people.size} people in the file '#{parser.file}'." | |
Zezan = Person.new(1,"Zezan","Tam","tam.zezan@gmail.com","+61432222428",1) | |
John = Person.new(2,"John","Smith","john.Smith@gmail.com","+61432222422",1) | |
parser.add_person(Zezan) | |
parser.add_person(John) | |
p parser | |
parser.save("dynamicwritetest.csv") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment