Writer316 Writer316 - 1 month ago 6
Ruby Question

My phonebook program doesn't sort my contact list correctly (ruby)?

I have this program with two classes: PhoneBook and PhoneContact. The goal of the program is to take a name with a phone number and the type of phone number it is (which is referred to as label). The PhoneContact class takes in a name and stores it as a contact. So, it works like this:

Bary_Bonds = PhoneContact.new(:work,'(111) 111-111', 'Barry Bonds')


The PhoneBook class takes in the phone contact and stores it in the directory. It can add, delete, find, and show all contacts in the phone book. I want to make a method that shows all the contacts in alphabet order.

This is my PhoneBook Class Code:

class PhoneBook
attr_accessor :contact_list

def initialize
@contact_list = []
end


This is my organize method:

def organize
puts @contact_list.each.map { |e| Array(e).join(", ") }.sort
end


I'm not sure what to do here. I know that my code for the organize method only outputs the numbers and doesn't output the names of the contact. So, the above code returns this output:

(111) 111-1111
(222) 222-5222
(555) 555-5555

Answer

As borbesaur mentioned, you need to sort by a name attribute on the PhoneContact objects. To customize the output, you'll need to implement a to_s method on PhoneContact:

class PhoneContact < Struct.new(:type, :number, :name)
  def to_s
    "#{name}, #{type}: #{number}"
  end 
end

You can use the method sort_by as a shortcut to sort your array of objects by an attribute:

  def organize
    puts @contact_list.sort_by(&:name)
  end 

That should result in output like this:

Barry Bonds, work: (555) 555-5555
Bobby Bonilla, work: (222) 222-5222
Doug Drabek, work: (111) 111-1111