Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Variables Ruby:唯一实例变量_Variables - Fatal编程技术网

Variables Ruby:唯一实例变量

Variables Ruby:唯一实例变量,variables,Variables,我在使@bank_余额成为该人独有的余额方面遇到了问题(Shehzan,John)。当我打电话给chase.deposit(我,200)时,我让Shehzan将200美元存入摩根大通。谢赞有300美元。谢赞的账户有200美元。这是正确的。但当我打电话给chase.deposit(朋友1300)后,我让John把300美元存入了JP摩根大通。约翰有700美元。约翰的账户有500美元。这是不正确的 约翰的账户应该只有300美元,而不是500美元。我相信现在发生的事情是,我将Shehzan账户中的20

我在使@bank_余额成为该人独有的余额方面遇到了问题(Shehzan,John)。当我打电话给chase.deposit(我,200)时,我让Shehzan将200美元存入摩根大通。谢赞有300美元。谢赞的账户有200美元。这是正确的。但当我打电话给chase.deposit(朋友1300)后,我让John把300美元存入了JP摩根大通。约翰有700美元。约翰的账户有500美元。这是不正确的

约翰的账户应该只有300美元,而不是500美元。我相信现在发生的事情是,我将Shehzan账户中的200美元存入@bank_balance,然后在执行chase.deposit(Friend1300)时将300美元存入@bank_balance

我想我需要在open_account方法中添加一些东西,以使@bank_余额对@name是唯一的。我只是不确定


我是Ruby新手,非常感谢您的帮助!谢谢

我想说,您的问题在于您对您的情况进行建模的方式,而不是Ruby实例变量的工作方式

特别是,感觉上你缺少了一个
账户
模型:一个
银行
维护一个
账户的列表
,每个
账户
都属于一个
,每个
都维护一个他们在不同
银行
账户列表


我假设这是一个学习练习(也就是说,你实际上不是在建立一个银行),所以我建议你考虑上面的问题,然后再试一次,而不是自己给自己写。< / P>没问题!祝你好运
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)