2016-11-02 37 views
-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 
+1

您能否请添加您收到的错误消息?恕我直言,问题在于你使用错误的语法来创建新的散列。使用'Hash.new'而不是'hash.new'。 –

+0

我相信你是对的。这是一个未定义的方法,但似乎contactList被声明为局部变量。 – Codes316

回答

0

因为你已经定义类的局部变量contactList,而你想有一个实例变量

删除此行

contactList = hash.new 

并添加以下方法:

def contactList 
    @contactList ||= {} 
end 

P.S.有没有这样的事情hash.new,你很可能意味着Hash.new

P.P.S.按照Ruby的命名规则,你的变量/方法名应该是蛇形的,而不是骆驼式的。 所以它应该是contact_list

相关问题