Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'csv'
- # Represents a person in an address book.
- class Contact
- @number_of_ids = CSV.read('contacts.csv').length
- attr_accessor :name, :email
- def initialize(name, email)
- # TODO: Assign parameter values to instance variables.
- @name = name
- @email = email
- end
- # Provides functionality for managing a list of Contacts in a database.
- class << self
- # Returns an Array of Contacts loaded from the database.
- def all
- # TODO: Return an Array of Contact instances made from the data in 'contacts.csv'.
- CSV.foreach('contacts.csv') do |row|
- puts row.join.to_s
- end
- puts "--- \n#{@number_of_ids} records in total"
- end
- # Creates a new contact, adding it to the database, returning the new contact.
- def create(name, email)
- # TODO: Instantiate a Contact, add its data to the 'contacts.csv' file, and return it.
- CSV.open('contacts.csv', 'ab') do |csv_object|
- a_row = ["#{@number_of_ids + 1}: " << "#{name} (#{email})"]
- csv_object << a_row
- end
- end
- # Returns the contact with the specified id. If no contact has the id, returns nil.
- def find(id)
- # TODO: Find the Contact in the 'contacts.csv' file with the matching id.
- CSV.foreach('contacts.csv') do |row|
- if row[0] == id
- puts row.join.to_s
- end
- end
- end
- # Returns an array of contacts who match the given term.
- 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').include? do |row|
- puts row.join.to_s
- end
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement