On 14.11.2010 13:17, Aaron Haas wrote:
> I=92m trying to create a simple address book in ruby.  It is made up fr=
om
> the following classes.  Address, Phone, Person, and AddressBook .  The
> Address, Phone, Person classes all work fine.  I=92m having problems wi=
th
> several methods in my AddressBook class.
>
> Add(person) needs to check if that person already exists.  I tried usin=
g
> 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=20
completely different aspect.  You basically have two options to improve=20
this:

1. Change #query to return an Array of found items.

2. Change #query so that it yields every matching entry to a block=20
passed to the method.

Advantage of both approaches is that you can reuse the query code in=20
different situations.  I would go with version 2 but 1 might be easier=20
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 =93exi=
t=94
> is entered. The add command which is the most complicated of the five
> works fine for a single time.  I can=92t 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=20
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=20
(output, prompting etc.).  That's usually considered bad because you mix =

logic with presentation.

> I=92m 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 thin=
k
> I should copy and paste let me know.

You could host this on github.  That way you also have version control=20
and can look at the path of evolution later.

Kind regards

	robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/