Recap - Contact List
Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 11 of 57.
Challenge
MediumComplete the class Contact. name, email and phone can be read. The setter email= stores the address in lower case and raises ArgumentError with invalid email: x when it has no @ or no . after the @. The setter phone= keeps only the digits and raises ArgumentError with invalid phone: x when fewer than 7 digits remain. initialize(name, email, phone) uses both setters. Two contacts are equal with == when their emails are equal. to_s returns Ada (ada@mail.io, 5551234).
The supplied code reads contacts as name,email,phone lines. It prints added Ada (ada@mail.io, 5551234), duplicate ada@mail.io for a contact equal to one already added, or the error message, and finally contacts: 2.
Your code goes in contact.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'contact'
# Supplied input/output code: keep it as it is
input = []
while (line = gets)
input << line.chomp
end
contacts = []
input.each do |line|
name, email, phone = line.split(",")
begin
contact = Contact.new(name, email, phone)
if contacts.include?(contact)
puts "duplicate #{contact.email}"
else
contacts << contact
puts "added #{contact}"
end
rescue ArgumentError => e
puts e.message
end
end
puts "contacts: #{contacts.size}"
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesInstance VariablesMethods and selfto_s and inspectRecap - Library Card7Polymorphism and Duck Typing
PolymorphismDuck TypingAbstract Methodscase and ClassesRecap - Payment Methods2Accessors and Self
Readers and WritersCustom Settersself in MethodsIdentity and EqualityRecap - Contact List8Special Methods
Equality and hashOperator MethodsIndexing and AppendingCustom CollectionsRecap - Fractions11Project: Library Management
Books and MembersBorrowing Books3Class Methods and Variables
Class MethodsClass Instance VariablesConstantsFactory MethodsRecap - Coupon CodesPractice on your own: Online Ruby compiler