class Person
attr_accessor :name, :name_balance
def initialize(name, name_balance=0)
@name = name
@name_balance = name_balance
puts "Hi, #{name}. You have $#{name_balance}!"
end
end
class Bank
attr_accessor :bank_name, :bank_balance
def initialize(bank_name)
@bank_name = bank_name
puts "#{bank_name} bank was just created."
end
def open_account(person, bank_balance=0)
@bank_balance = bank_balance
puts "#{person.name}, thanks for opening an account at #{bank_name}!"
end
def deposit(person, amount)
@amount = amount
@bank_balance += amount
person.name_balance -= amount
puts "#{person.name} deposited $#{amount} to #{bank_name}. #{person.name} has $# {person.name_balance}. #{person.name}'s account has $#{bank_balance}."
end
end
chase = Bank.new("JP Morgan Chase")
wells_fargo = Bank.new("Wells Fargo")
me = Person.new("Shehzan", 500)
friend1 = Person.new("John", 1000)
chase.open_account(me)
chase.open_account(friend1)
wells_fargo.open_account(me)
wells_fargo.open_account(friend1)
chase.deposit(me, 200)
chase.deposit(friend1, 300)
我在使@bank_balance
对Person(Shehzan,John)唯一时遇到了问题。当我调用chase.deposit(me, 200)
时,我得到
Shehzan向摩根大通存入了200美元。Shehzan有300美元。Shehzan的帐户有200美元。
这是正确的但是当我在调用chase.deposit(me, 200)
之后再调用chase.deposit(friend1, 300)
时,我得到
约翰在摩根大通银行存了300美元。约翰有700美元。约翰的账户里有500美元。
这是不正确的
约翰的账户应该只有300美元,而不是500美元。我相信发生的事情是我将Shehzan帐户中的200美元存储在@bank_balance
中,然后在执行chase.deposit(friend1, 300)
时将300美元添加到@bank_balance
中。
我想我需要向open_account
方法添加一些东西,使@bank_balance
对于@name
是唯一的。我只是不确定...
1条答案
按热度按时间lrl1mhuk1#
我会说你的问题在于你建模的方式,而不是Ruby的示例变量的工作方式。
特别是,感觉你错过了一个
Account
模型:Bank
维护Accounts
的列表,每个Account
由Person
拥有,每个Person
维护其Accounts
在不同Banks
的列表。我假设这是一个学习练习(即,你实际上并没有建立一个银行),所以我建议你考虑一下上面的内容,然后再试一次,而不是自己写。