2014-07-02 75 views
0

我在紅寶石銀行問題的工作,並試圖寫的存款方法的代碼時,我不斷碰到這個錯誤來。我想存款方式推出一個看跌聲明,稱此人有足夠的現金讓這個存款和狀態量,或者它指出,他們沒有足夠的現金存款。它在我的irb中說這個錯誤:紅寶石:問題與一個未定義的方法錯誤

NoMethodError: undefined method `<' for nil:NilClass 
from banking2.rb:30:in `deposit' 
from banking2.rb:59:in `<top (required)>' 

有人能幫我找到我的錯誤嗎?我嘗試了幾個選項,但無法弄清楚。

class Person 

    attr_accessor :name, :cash_amount 

    def initialize(name, cash_amount) 
    @name = name 
    @cash_amount = @cash_amount 
    puts "Hi, #{@name}. You have #{cash_amount}!" 
    end 
end 

class Bank 

    attr_accessor :balance, :bank_name 

    def initialize(bank_name) 
    @bank_name = bank_name 
    @balance = {} #creates a hash that will have the person's account balances 
    puts "#{bank_name} bank was just created." 
    end 

    def open_account(person) 
    @balance[person.name]=0 #adds the person to the balance hash and gives their balance 0 starting off. 
    puts "#{person.name}, thanks for opening an account at #{bank_name}." 
    end 

    def deposit(person, amount) 
    #deposit section I can't get to work 
    if person.cash_amount < amount 
     puts "You do not have enough funds to deposit this #{amount}." 
    else 
     puts "#{person.name} deposited #{amount} to #{bank_name}. #{person.name} has #{person.cash_amount}. #{person.name}'s account has #{@balance}." 
    end 
    end 

    def withdraw(person, amount) 

    #yet to write this code 

    # expected sentence puts "#{person.name} withdrew $#{amount} from #{bank_name}. #{person.name} has #{person.cash_amount} cash remaining. #{person.name}'s account has #{@balance}. " 

    end 

    def transfer(bank_name) 
    end 

end 


chase = Bank.new("JP Morgan Chase") 
wells_fargo = Bank.new("Wells Fargo") 
person1 = Person.new("Chris", 500) 
chase.open_account(person1) 
wells_fargo.open_account(person1) 
chase.deposit(person1, 200) 
chase.withdraw(person1, 1000) 
+0

可以person.cash_amount在任何情況下零? – ravi1991

回答

2

變化這在初始化方法上的人:

@cash_amount = @cash_amount 

要這樣:

@cash_amount = cash_amount 

您增加了額外的@符號,所以你設置@cash_amount到@cash_amount。 Ruby中未初始化的實例變量的默認值爲nil

+0

謝謝!有時候,最簡單的錯誤就是抓住你! :) – user3604867

+0

如果您認爲這是一個很好的答案,並且您想接受它,請按下點數下的綠色支票,@ user3604867 – Piccolo

+0

這兩個答案都很棒!再次感謝你! – user3604867

2

唯一的地方,你有一個<person.cash_amount < amount,所以錯誤是從那裏來 - person.cash_amount爲零。

看看cash_amount在您的人員初始值設定項中定義的位置 - 您正在通過def initialize(name, cash_amount)但您打電話給@cash_amount = @cash_amount

刪除第二個@,因此您實際上將指定爲您在cash_amount中傳遞的值。

+0

哦天哪,謝謝你抓到! – user3604867

+0

再次感謝您的幫助! – user3604867