Codes316 Codes316 - 1 month ago 5
Ruby Question

Why doesn't my hash work in Ruby?

I have this phonebook program that looks up all the contacts, deletes a contact, and adds a contact. I created a hash global variable called contactList. However, the program fails to recognize this. What did I do wrong?

class PhoneBook
contactList = hash.new
def Add(newContact = {})
flag = false
if newContact.length < 1
return flag
else
flag = true
newContact.collect do |name, number|
contactList[name] = number
end
return flag
end
end

def delete (targetName)
if !contactList.has_key?(targetName)
return false
else
contactList.delete(targetName)
return true
end

end
def displayContact (targetName)
number = -1
if contactList.has_key?(targetName)
number = contactList(targetName)
puts "Contact name : #{targetName}, Contact Number, #{number}"
else
puts "#{targetName} doesn't exist in the phonebook"
end
end
def displayAllContacts
if !contactList.empty?
contactList.each {|name, number| puts "Contact name: #{name}, contact number #{number}" }
else
puts "You don't have any contact details your phonebook"
end
end
end

Answer

Because you have defined class local variable contactList, whereas you wanted to have an instance variable.

Remove this line

contactList = hash.new

and add the following method:

def contactList
  @contactList ||= {}
end

P.S. there is no such thing as hash.new, you most likely meant Hash.new.

P.P.S. By Ruby naming conventions your variables/methods names should be snake-cased, not camel cased. So it should be contact_list.