account.rb:17:in `withdraw': nil:NilClass 的未定义方法 `-' (NoMethodErro r)

account.rb:17:in `withdraw': undefined method `-' for nil:NilClass (NoMethodErro r)

我在执行表单终端时遇到错误。

withdraw : undefined method '-'

我不明白为什么。我试过用 sublime 和 notepad++ 编辑。

class Account
    def initialize(name, balance, phone_no)
        @name = name
        @balance = balance
        @phone_no = phone_no
    end

    def deposit(amount)
        @amount += amount
    end

    def withdraw(amount)
        @amount -= amount
    end

    def display()
        puts "Name: " + @name
        puts "Phone number: " + @phone_no.to_s
        puts "Balance: " + @balance.to_s
    end

    def transfer(amount, target_account)
        @balance -= amount
        target_account.deposit(amount)
    end

    def status
        return @balance
    end
end

这两个方法不应该在@balance上操作吗?

def deposit(amount)
    @balance += amount
end

def withdraw(amount)
    @balance -= amount
end

@amountnil。你这样做

@amount = nil - amount

nil没有-方法

@amount 在您的 depositwithdraw 方法中是 nil。而且您不能在 nil 对象上调用 - 方法。可能您将 @balance 拼错为 @amount?

def deposit(amount)
  @balance += amount
end

def withdraw(amount)
  @balance -= amount
end