Skip to content

Instantly share code, notes, and snippets.

@stupeters187
Created April 5, 2016 00:01
Show Gist options
  • Save stupeters187/35c95559fa38b870da510517729949a4 to your computer and use it in GitHub Desktop.
Save stupeters187/35c95559fa38b870da510517729949a4 to your computer and use it in GitHub Desktop.
# require './contacts.csv'
require 'csv'
# Represents a person in an address book.
# The ContactList class will work with Contact objects instead of interacting with the CSV file directly
class Contact
attr_accessor :name, :email
# Creates a new contact object
# @param name [String] The contact's name
# @param email [String] The contact's email address
def initialize(name, email)
@name = name
@email = email
end
# Provides functionality for managing contacts in the csv file.
class << self
# Opens 'contacts.csv' and creates a Contact object for each line in the file (aka each contact).
# @return [Array<Contact>] Array of Contact objects
def all
CSV.foreach('contacts.csv') do |contact|
puts contact.inspect
end
end
# Creates a new contact, adding it to the csv file, returning the new contact.
# @param name [String] the new contact's name
# @param email [String] the contact's email
def create(name, email)
# TODO: Instantiate a Contact, add its data to the 'contacts.csv' file, and return it.
contact = Contact.new(name, email)
number_of_contacts = CSV.read('contacts.csv').length
CSV.open('contacts.csv', 'a') do |contacts_csv|
contacts_csv << [number_of_contacts + 1, contact.name, contact.email]
end
end
# Find the Contact in the 'contacts.csv' file with the matching id.
# @param id [Integer] the contact id
# @return [Contact, nil] the contact with the specified id. If no contact has the id, returns nil.
def find(search_id)
# TODO: Find the Contact in the 'contacts.csv' file with the matching id.
# prompt the user for the id #
# read the contacts file
# go through each [0] location of the contacts array
# match the contact id with the user input
CSV.foreach('contacts.csv') do |contact|
if search_id == contact[0].to_i
puts contact
end
end
end
# Search for contacts by either name or email.
# @param term [String] the name fragment or email fragment to search for
# @return [Array<Contact>] Array of Contact objects.
def search(term)
# TODO: Select the Contact instances from the 'contacts.csv' file whose name or email attributes contain the search term.
CSV.foreach('contacts.csv') do |contact|
if contact.include?(term)
p contact
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment