From: Aaron Haas Date: 2010-11-13T00:43:17+09:00 Subject: help sorting objects by their instance field I'm trying to figure out how to sort objects in an array by one of their instance variables, in this case last name. The person class has a first name, last name, and an address object. The address book class is made up of an array of persons. How do I sort the array of persons in alphabetically by the persons last name instance fields. I added a getLastname method to the persons class, but I'm not sure on the logic. [CODE] class Person attr_accessor :fname, :lname, :address # initializer def initialize @fname = @lname = "" # since address is an object @address = Address.new end # assign given values to Person object def crPerson (aFname, aLname, aAddress) @fname = aFname @lname = aLname @address = aAddress end def get_lname return @lname end # string representation of Person # note the syntax: address.to_s (to call the to_s instance method of Address class) def to_s @fname + " " + @lname + "\n" + "\n" + address.to_s end end [/CODE] [CODE] class AddressBook # class variable. keeps track of number of address book entries @@instances = 0 # no attr_accessor # don't want the user to have direct access to @persons def initialize @persons = [] # starts with empty array end # add person to address book def add(person) @persons += [person] @@instances += 1 end # delete person from address book def remove(person) @persons.delete(person) @@instances -= 1 end # totally lost on this part # print sorted by last name method using person's get_lname method def print_addresses @persons.each { |p| persons[p].get_lname.sort } end # close while loop # print sorted array @persons.each { |p| yield p } end end [/CODE] -- Posted via http://www.ruby-forum.com/.