我在紅寶石銀行問題的工作,並試圖寫的存款方法的代碼時,我不斷碰到這個錯誤來。我想存款方式推出一個看跌聲明,稱此人有足夠的現金讓這個存款和狀態量,或者它指出,他們沒有足夠的現金存款。它在我的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)
可以person.cash_amount在任何情況下零? – ravi1991