From: Lyle Johnson Date: 2009-11-25T04:02:58+09:00 Subject: Re: Help with each_with_index method On Tue, Nov 24, 2009 at 12:00 PM, Chris Pelow wrote: > Basically I have 5 names entered into an array. They have a firstname > and surname. A middlename is then optional. > What I want to do is to print out the names like this.. > John Seymour Smith > Peter        Jones > Mary         Walsh > > So it yields the middlename and prints it out if it has one. For starters, your Person class doesn't need to mix-in Enumerable, and it doesn't need an "each" method. The array (people) that you're adding Person instances to is the thing that is enumerable, and it has its own each method built-in. So a trimmed down Person class could look like so: class Person include Comparable attr_accessor :firstname, :middlename, :surname def initialize (firstname, middlename, surname) @firstname = firstname @middlename = middlename @surname = surname end def to_s "Hello my name is #@firstname #@surname and i'm #@age" end def <=> (other) (self.firstname) <=> (other.firstname) end end Your comparison method (the <=> method) isn't quite right, since it's only comparing their first names, but I'll let you ponder how you might improve that. You're on the right track. Now, given your requirement for how you'd like the names to be printed, I think I'd also add a full_name() method to the Person class, something like: class Person def full_name unless middlename.empty? "#{firstname} #{middlename} #{surname}" else "#{firstname} #{surname}" end end end Finally, there are several issues with the bit at the end where you're trying to iterate over the array of people. You have two loops (an #each loop and then an #each_with_index loop) nested inside each other. For the inner loop, the "index" and "person" arguments that each_with_index() passes into the block aren't instance variables, so you just refer to them as "index" and "person", not "@index" and "@person". I'd change that last bit to look like this: people_sorted = people.sort people_sorted.each_with_index do |person, index| puts "Hi there #{index} #{person.full_name}!" end Hope this helps, Lyle