К вашему сведению: впервые я написал Ruby.
Мы должны написать программу адресной книги.У меня есть много частей, работающих на данный момент, но наткнулся на то, что я не понимаю.
Я добавляю контакты в адресную книгу статически перед запуском программы.Затем я пытаюсь, чтобы пользователь добавил контакт динамически.Когда я распечатываю эту адресную книгу, добавленные статически контакты распечатываются в соответствии с ожидаемым форматированием, но динамически добавленные - повсюду.
Я добавил весь свой код здесь.Это большой кусок, но не так уж и плохо ...
# Address class
class Address
attr_accessor :street, :city, :state, :zip
# default constructor
def initialize(*args)
if (args.size == 0 )
@street = @city = @state = @zip = ""
elsif (args.size == 4)
@street = args[0]
@city = args[1]
@state = args[2]
@zip = args[3]
else
puts('Constructor takes 0 or 4 arguments. No address information has been set.')
end
end
# string representation of address
def to_s
" " + @street + "\n" + \
" " + @city + " " + @state + ", " + @zip
end
end
# Person class which holds full name, phone, and
# address as an object
class Person
attr_accessor :fname, :lname, :phone, :address
def initialize(*args)
if (args.size == 0 )
@fname = @lname = @phone = ""
@address = Address.new
elsif (args.size == 4)
@fname = args[0]
@lname = args[1]
@phone = args[2]
@address = args[3]
else
puts('Incorrect number of arguments.')
end
end
# returns full name
def full_name
@lname + ", " + @fname
end
def to_s
" " + full_name + "\n" + \
@address.to_s + "\n" + \
" " + @phone
end
end
# AddressBook class to hold addresses
class AddressBook
def initialize
# empty array
@persons = []
end
# adds a person to the address book
def add(person)
@persons += [person]
@persons = @persons.sort{|a,b| by_name(a,b)}
end
def by_name(a,b)
if a.lname == b.lname
a.fname <=> b.fname
else
a.lname <=> b.lname
end
end
# removes a person from the address book
def remove(person)
# Use Array#delete
@persons.delete(person)
end
def to_s
add_book = ""
for p in @persons do
add_book += p.to_s + "\n\n"
end
return add_book
end
end
#
# Here I add three contacts in two different ways
#
#
# FIRST ONE
#
sandy_addr = Address.new
sandy_addr.street = "324 Campus Dr."
sandy_addr.city = "College Park"
sandy_addr.state = "OH"
sandy_addr.zip = "55555"
sandy = Person.new
sandy.fname = "Sandy"
sandy.lname = "Koh"
sandy.phone = "651-442-5710"
sandy.address = sandy_addr
#
# SECOND ONE
#
bill_addr = Address.new('536 Green Rd.', "Saint Paul", "MN", "56545")
bill = Person.new('William', 'Perry', '675-778-6754', bill_addr)
#
# THIRD ONE
#
angela_addr = Address.new('3390 Crookston Rd.', "Miami", "FL", "78654")
angela = Person.new('Angela', 'Anderson', '345-748-1754', angela_addr)
# Contacts added to the Address Book
@addressBook = AddressBook.new
@addressBook.add(sandy)
@addressBook.add(angela)
@addressBook.add(bill)
# Main method loop that runs the program
# Allows you to enter a contact, print a list of
# contacts and exit the program
def loop(addBook)
selection = 0
until(selection == 5)
puts("Wlecome to the Address Book\n")
puts("1. Add a Contact\n")
puts("2. Delete a Contact\n")
puts("3. Retrieve a Contact\n")
puts("4. Print all Contacts\n")
puts("5. Exit Address Book\n")
selection = gets().to_i
if(selection == 1)
addContact(addBook)
elsif(selection == 2)
#delete_contact
elsif(selection == 3)
#retrieve_contact
elsif(selection == 4)
puts(addBook)
end
end
end
def addContact(addBook)
print("Enter First Name: ")
fname = gets()
print("Enter Last Name: ")
lname = gets()
print("Enter Phone Number: ")
phone = gets()
print("Enter Street Address: ")
street = gets()
print("Enter City: ")
city = gets()
print("Enter State: ")
state = gets()
print("Enter Zip Code ")
zip = gets()1
newAddress = Address.new(street, city, state, zip)
newPerson = Person.new(fname, lname, phone, newAddress)
addBook.add(newPerson)
out = %q/#{fname} #{lname} has been added to the Address Book./
puts(out)
end
loop(@addressBook)