-1
我有這個電話簿程序,查找所有聯繫人,刪除聯繫人,並添加聯繫人。我創建了一個名爲contactList
的哈希全局變量。但是,該程序未能認識到這一點。我做錯了什麼?爲什麼我的散列不能在Ruby中工作?
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
您能否請添加您收到的錯誤消息?恕我直言,問題在於你使用錯誤的語法來創建新的散列。使用'Hash.new'而不是'hash.new'。 –
我相信你是對的。這是一個未定義的方法,但似乎contactList被聲明爲局部變量。 – Codes316