2014-07-02 46 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