Amulya Amulya - 3 months ago 14
Ruby Question

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

I am getting error while executing form terminal.

withdraw : undefined method '-'


I do not understand why. I have tried editing with sublime and 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

Answer

Shouldn't these two methods operate on @balance?

def deposit(amount)
    @balance += amount
end

def withdraw(amount)
    @balance -= amount
end

@amount is nil. You're doing so

@amount = nil - amount

and nil doesn't have a - method

Comments