Menu
Coddy logo textTech

Recap - Contact List

Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 11 of 57.

challenge icon

Challenge

Medium

Complete 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

Practice on your own: Online Ruby compiler