Ruby:未定义方法错误的问题

时间:2014-07-02 13:38:40

标签: ruby

我正在研究ruby银行问题,在尝试编写存款方法的代码时,我一直遇到这个错误。我希望通过存款方式发出一份声明,说明这个人有足够的现金来存入这笔存款和国家金额,或者说它没有足够的现金存款。它在我的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)

2 个答案:

答案 0 :(得分:2)

您拥有<的唯一地点位于person.cash_amount < amount,因此错误来自那里 - person.cash_amount为零。

查看人员初始化程序中定义cash_amount的位置 - 您正在传递def initialize(name, cash_amount)但是您正在调用@cash_amount = @cash_amount

删除第二个@,以便您实际为@cash_amount分配您在cash_amount中传入的值。

答案 1 :(得分:2)

在Person:

上的初始化方法中更改此项
@cash_amount = @cash_amount

对此:

@cash_amount = cash_amount

您添加了额外的@符号,因此您将@cash_amount设置为@cash_amount。未初始化的实例变量的默认值是Ruby中的nil