On 14.11.2010 13:17, Aaron H. wrote:
Im trying to create a simple address book in ruby. It is made up from
the following classes. Address, Phone, Person, and AddressBook . The
Address, Phone, Person classes all work fine. Im having problems with
several methods in my AddressBook class.
Add(person) needs to check if that person already exists. I tried using
my query method but it only prints the name to the screen. Can I make
it also return an person object to use as a comparison?
You should remove the printing from the finding because this is a
completely different aspect. You basically have two options to improve
this:
-
Change #query to return an Array of found items.
-
Change #query so that it yields every matching entry to a block
passed to the method.
Advantage of both approaches is that you can reuse the query code in
different situations. I would go with version 2 but 1 might be easier
to understand at first. If you do 2 you could code like this
def print_query(name)
query name do |person|
puts person
end
end
def query_first(name)
query name do |person|
return person
end
nil
end
def add(name, …)
raise “Person known already” if query_first(name)
…
end
The prompt method should take a command (add, print, remove, find,
exit) then depending on which command ask the user for required
information. The command prompts should run continuously until exit
is entered. The add command which is the most complicated of the five
works fine for a single time. I cant figure out how to implement a
while condition to keep it going without getting errors.
I would create a class per command. This class can contain the prompt
text as well as the evaluation logic. You could then stuff instances of
those classes in a Hash and just look them up via command.
But: I would remove the code from AddressBook. Currently you are mixing
model code (i.e. data management of address books) with user interface
(output, prompting etc.). That’s usually considered bad because you mix
logic with presentation.
Im also having problems with the remove method logic. I built the
remove method to take a variable name as a parameter, but the command
prompt would require an first and last name instance fields from the
person class.
I’m getting close just a few tweaks here and there.
This code is getting long one so I just attached the file. If you think
I should copy and paste let me know.
You could host this on github. That way you also have version control
and can look at the path of evolution later.
Kind regards
robert