2014-11-09 39 views
0

你好堆棧器我正在調試我的第一個實現一個簡單的銀行(撤回,存款,轉讓等)的紅寶石應用程序。我需要詢問用戶的卡號,然後將其與哈希值進行比較,以獲取與該卡相關聯的人員。我似乎無法得到的價值,雖然它似乎我將一個相同的數組與哈希鍵進行比較。在Ruby中使用數組作爲散列鍵

def addAccount(person,card,key,account) 
     @key = "Kudzu" 
     if(key === @key) 
      $people[card["card_number"]] = person 
      $accounts[card["card_number"]] = account 
      return true 
     else 
      puts "Access Denied: atm.addAccount" 
      return false 
     end 
    end 



    def start_trans() 
     while(true) 
      STDOUT.flush 
      puts "Insert Card (1234 5678 9123 4567) >> " 
      temp = gets.chomp 
      @card = temp.split(" ") 
      puts @card 
      puts @card.class 
      puts $people 
      @person = $people[@card] 
      if(@person) 
       @account = $accounts[@card] 
       get_pin() 
       break 
      else 
       puts "Didn't catch that try again" 
      end 
     end 
    end 

我的輸出:

Insert Card (1234 5678 9123 4567) >> 
6327 6944 9964 1048 
6327 
6944 
9964 
1048 
Array 

{[6327, 6944, 9964, 1048]=>#<Person:0x2ae5548 @zip="12345", @cash="123", @name="r", @card={"card_number"=>[6327, 6944, 9964, 1048], "exp_month"=>11, " 
exp_year"=>2018, "security_code"=>468, "zip_code"=>"12345", "pin"=>"1234"}, @account=#<Account:0x2ae5530 @person=#<Person:0x2ae5548 ...>, @atm=#<Atm:0 
x2ae5500>, @name="r", @balance=nil, @accounts=nil, @key="Kudzu", @pin="1234", @card={"card_number"=>[6327, 6944, 9964, 1048], "exp_month"=>11, "exp_ye 
ar"=>2018, "security_code"=>468, "zip_code"=>"12345", "pin"=>"1234"}>>} 

Didn't catch that try again 
Insert Card (1234 5678 9123 4567) >> 

我之前和之後我把$的人只是爲了可讀性添加了一個空行,以我的輸出就在這裏。

回答

0

如果您在$people哈希定義爲

$people = {["6327", "6944", "9964", "1048"] => blabla... } 

你會得到puts $people以下的輸出:

{["6327", "6944", "9964", "1048"] => blabla... } 

從您發佈的輸出,看來你的存儲卡號碼作爲數組$people哈希鍵。但是,然後您嘗試使用字符串的數組來查詢關聯值,這肯定無效。

您需要將輸入轉換成數的數組您查詢的相關數據之前:

puts "Insert Card (1234 5678 9123 4567) >> " 
temp = gets.chomp 
@card = temp.split(" ").map(&:to_i) 
.... 

一般來說,這是不好的做法是使用Array作爲Ruby的哈希鍵,因爲Array它可變的,這可能導致密鑰和密鑰哈希碼不一致。我會考慮使用Symbol卡號碼:

# update people 
$people_updated = Hash[ $people.map{|k, v| [k.join.to_sym, v]} ] 

# query 
puts "Insert Card (1234 5678 9123 4567) >> " 
temp = gets.chomp 
@card = temp.scan(/\d+/).join.to_sym 
... 
+0

@Ane肖由於只是把我投入一個哈希並顯示它意識到了這一點(我沒想到不幸的是在發佈之前嘗試此)。刪除我的答案並接受你的答案。感謝你的真棒。 – spintron 2014-11-09 05:04:12