Reputation: 143
I am working on a ruby banking problem and I keep coming across this error when trying to write the code for the deposit method. I would like the deposit method to put out a puts statement saying this person has enough cash to make this deposit and state amount, or it states they do not have enough cash to deposit. It says this error in my irb:
NoMethodError: undefined method `<' for nil:NilClass
from banking2.rb:30:in `deposit'
from banking2.rb:59:in `<top (required)>'
Can someone please help me find my error? I've tried several options but am not able to figure it out.
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)
Upvotes: 0
Views: 179
Reputation: 35788
Change this in your initialize method on Person:
@cash_amount = @cash_amount
To this:
@cash_amount = cash_amount
You added an extra @ sign, so you set @cash_amount to @cash_amount. The default value for an uninitialized instance variable is nil
in Ruby.
Upvotes: 2
Reputation: 25049
The only place you have a <
is in person.cash_amount < amount
, so the error is coming from there - person.cash_amount
is nil.
Look at where cash_amount
is being defined in your Person initializer - you are passing in def initialize(name, cash_amount)
but then you are calling @cash_amount = @cash_amount
!
Remove the second @
so you are actually assigning @cash_amount
with the value you are passing in in cash_amount
.
Upvotes: 2