Hi --
Hi all,
I've just started my journey as a ruby developer, and I'm going through
a couple of exercises that one of my professors sent me, to allow me
figure out the syntax. It's not for an assignment, merely for practice
(I need it). My code looks like Java, it's not elegant, it's slow, but
little by little, right?
Yes, but a little can go a long way You definitely need to let Ruby
do much more of the work.
I'm having a problem with my code. It's attached, and if someone could
look at it, that would be great. I can't figure out what I'm doing
wrong. I think it's something wrong with my for loop. Basically, the
code is supposed to find "spies" for all the entries, but someone cannot
"spy" on a person with their same last name, or themselves. The goal is
to print the list of spies all out. Thank you in advance!
I had trouble with your input file (see my separate post to this list).
I've changed it so that it uses spaces instead of non-printing
characters. I have then created the following implementation:
http://pastie.org/1048517
Not fully tested, but I wanted to insinuate at least a partial test
suite in there You can run the tests by giving the command-line
argument "test". Otherwise it will print out the results of the spy
checking.
A couple of key points:
Very rarely do you have to maintain explicit counters in Ruby. The
language full of facilities for traversing collections. If you can get
objects into collections, you can then use things like "each" and "find"
instead of maintaining counters. I use find to get the first person, if
there is one, from the rand_spies array on whom the current person is
allowed to spy.
(I think your original infinite loop problem was because the counter was
misplaced in relation to the do/end nesting. Less nesting makes those
things less likely and easier to fix.)
I've put much more of the business logic of the Person class (which I
singularized) into the class. For example, Person objects can now tell
you whether or not they're allowed to spy on someone else. I may or may
not have the logic exactly right, but the point is to put the knowledge
of Person business into the Person objects, rather than inlining it in
the code outside.
Another win is the to_s method, which lets me interpolate a person
object into a string without having to do the formatting explicitly. Of
course, I can always use a different/explicit format if I need to, but
to_s can at least cover the most common case.
Finally: there are different ways to do just about everything I've done
here, including the algorithms as well as the language-specific
techniques. So keep tinkering
David
···
On Sat, 17 Jul 2010, James Rasmussen wrote:
--
David A. Black, Senior Developer, Cyrus Innovation Inc.
The Ruby training with Black/Brown/McAnally
Compleat Philadelphia, PA, October 1-2, 2010
Rubyist http://www.compleatrubyist.com