2014-10-30 37 views
0

我正在創建一個可以創建和更新信用卡的簡單CC類。爲此,我創建了cc_bal {}作爲實例對象,以便它可以更新尊重信用卡。散列是爲了保存和更新一個人以及他們cc上的金額。我最終想起來時創建,而不是更新量當在簡單信用卡類中創建哈希值時發生錯誤

繼承人的代碼原有量的輸出:

class CC 

    def initialize(cc_name, cc_bal = {}, open_cc = false) 
     @cc_name = cc_name 
     @cc_bal = cc_bal 
     @open_cc = open_cc 
    end 

    def create(initAmount, person) 
     if initAmount > 0 
      @open_cc = true 
      @cc_bal[:person]=initAmount 
      puts "congrats #{person} on opening your new #{@cc_name} CC! with $#{@cc_bal[:person]}" 
     else 
      puts "sorry not enough funds" 
     end 
    end 

    def update(amount, person) 
     if @open_cc == true 
      @cc_bal[:person] + amount 
     else 
      puts "sorry no account created, #{person}" 
     end 
     puts "#{person} has CC balance of #{@cc_bal[:person]}" 
    end 
end 


#chase = Bank.new("JP Morgan Chase") 
#wells_fargo = Bank.new("Wells Fargo") 
me = Person.new("Shehzan", 500) 
friend1 = Person.new("John", 1000) 
#chase.open_account(me) 
#chase.open_account(friend1) 
#wells_fargo.open_account(me) 
#wells_fargo.open_account(friend1) 
#chase.deposit(me, 200) 
#chase.deposit(friend1, 300) 
#chase.withdraw(me, 50) 
#chase.transfer(me, wells_fargo, 100) 
#chase.deposit(me, 5000) 
#chase.withdraw(me, 5000) 
#puts chase.total_cash_in_bank 
#puts wells_fargo.total_cash_in_bank 
credit_card = CC.new("Visa") 
credit_card.create(10,me) 
credit_card.update(50,me) 
credit_card.create(20,friend1) 
credit_card.update(40,friend1) 

請無視被註釋掉的函數調用。

任何想法爲什麼CC沒有更新?

回答

1
if @open_cc == true 
    @cc_bal[:person] + amount 
else 

您增加金額,但不會在任何地方設置新值。它應該是

if @open_cc == true 
    @cc_bal[:person] += amount 
else 

注意。代碼需要一些嚴肅的重構和清理。

+0

嚴重是輕描淡寫。如果這是處理真錢,我會非常擔心。 – tadman 2014-10-30 21:43:50

+0

根據傳遞給創建和更新的參數集,我還猜測它是'@cc_bal [person]',而不是'@cc_bal [:person]'。 – moonfly 2014-10-30 22:18:27

+0

對不起,編程有點新 - 重構和清理代碼時,你會發現什麼?拋開所有評論和膚淺的東西,邏輯是否有問題? – rahul2001 2014-10-30 23:49:23