Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. require 'csv'
  2.  
  3. # Represents a person in an address book.
  4. class Contact
  5. @number_of_ids = CSV.read('contacts.csv').length
  6. attr_accessor :name, :email
  7.  
  8. def initialize(name, email)
  9. # TODO: Assign parameter values to instance variables.
  10. @name = name
  11. @email = email
  12. end
  13.  
  14. # Provides functionality for managing a list of Contacts in a database.
  15. class << self
  16.  
  17. # Returns an Array of Contacts loaded from the database.
  18. def all
  19. # TODO: Return an Array of Contact instances made from the data in 'contacts.csv'.
  20. CSV.foreach('contacts.csv') do |row|
  21. puts row.join.to_s
  22. end
  23. puts "--- \n#{@number_of_ids} records in total"
  24. end
  25.  
  26. # Creates a new contact, adding it to the database, returning the new contact.
  27. def create(name, email)
  28. # TODO: Instantiate a Contact, add its data to the 'contacts.csv' file, and return it.
  29. CSV.open('contacts.csv', 'ab') do |csv_object|
  30. a_row = ["#{@number_of_ids + 1}: " << "#{name} (#{email})"]
  31. csv_object << a_row
  32. end
  33. end
  34.  
  35. # Returns the contact with the specified id. If no contact has the id, returns nil.
  36. def find(id)
  37. # TODO: Find the Contact in the 'contacts.csv' file with the matching id.
  38. CSV.foreach('contacts.csv') do |row|
  39. if row[0] == id
  40. puts row.join.to_s
  41. end
  42. end
  43. end
  44.  
  45. # Returns an array of contacts who match the given term.
  46. def search(term)
  47. # TODO: Select the Contact instances from the 'contacts.csv' file whose name or email attributes contain the search term.
  48. CSV.foreach('contacts.csv').include? do |row|
  49. puts row.join.to_s
  50. end
  51. end
  52. end
  53. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement