Ruby:独特的实例变量

时间:2014-11-25 16:38:19

标签: variables

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


puts Person.instance_variables
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(我,200)我得到 Shehzan向摩根大通存入200美元。 Shehzan有300美元。 Shehzan的账户有200美元。这是正确的。但是当我在调用 chase.deposit(我,200)之后调用 chase.deposit(friend1,300)时,我得到 John向摩根大通存入300美元。约翰有700美元。 这个帐号有500美元。这是不正确的。

约翰的账户应该只有300美元,而不是500美元。我相信发生的事情是我在 @bank_balance 中存储Shehzan帐户中的200美元,然后在执行时将<300>添加到 @bank_balance chase.deposit(friend1,300)

我想我需要在 open_account 方法中添加一些内容,使 @name @name 唯一。我只是不确定...

我是Ruby的新手,所以非常感谢任何帮助!谢谢!

1 个答案:

答案 0 :(得分:0)

我会说你的问题是你模仿你的情况的方式,而不是Ruby的实例变量的工作方式。

特别感觉您错过了Account模型:Bank维护的Accounts列表中,每个Account都归Person所有每个Person都会在各种Accounts维护一个Banks列表。

我认为这是一个学习练习(即,你实际上并没有设立银行),所以我建议你考虑上面的内容,然后再试一次,而不是自己为你写。