Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Build an Address Book in Ruby!
You have completed Build an Address Book in Ruby!
Preview
Saving
Documentation Links
- Ruby IO Documentation
- Ruby YAML Documentation
- Ruby Psych Documentation - This is the class YAML interfaces with.
Code Samples
require "./contact"
require "yaml"
class AddressBook
attr_reader :contacts
def initialize
@contacts = []
open()
end
def open
if File.exist?("contacts.yml")
@contacts = YAML.load_file("contacts.yml")
end
end
def save
File.open("contacts.yml", "w") do |file|
file.write(contacts.to_yaml)
end
end
def run
loop do
puts "Address Book"
puts "a: Add Contact"
puts "p: Print Address Book"
puts "s: Search"
puts "e: Exit"
print "Enter your choice: "
input = gets.chomp.downcase
case input
when 'a'
add_contact
when 'p'
print_contact_list
when 's'
print "Search term: "
search = gets.chomp
find_by_name(search)
find_by_phone_number(search)
find_by_address(search)
when 'e'
save()
break
end
puts "\n"
end
end
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Now, this is gonna work in
a couple different parts.
0:00
So for right now, let's just go ahead and
write two methods, open.
0:03
And save.
0:10
Open and save are gonna be called at
different points in the address book.
0:12
Now, we've got this run method which
basically controls our entire program.
0:18
We could add contacts, print the address
book, search through the contacts or exit.
0:22
So before we exit, what we're
gonna do is call the save method.
0:29
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up