2014-11-25 30 views
2

我有以下代码:红宝石:从其他类使用实例变量

class Person 

attr_reader :name, :balance 
def initialize(name, balance=0) 
    @name = name 
    @balance = balance 
    puts "Hi, #{name}. You have $#{balance}!" 
end 
end 

class Bank 

attr_reader :bank_name 
def initialize(bank_name) 
    @bank_name = bank_name 
    puts "#{bank_name} bank was just created." 
end 

def open_account(name) 
    puts "#{name}, thanks for opening an account at #{bank_name}!" 
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.open_account(me)我得到的结果Person:0x000001030854e0, thanks for opening an account at JP Morgan Chase!。我似乎获得unique_id(?),而不是创建me = Person.new("Shehzan", 500),时我分配给@name的名称。我读过很多关于类/实例变量的知识,但似乎无法弄清楚。

回答

2

这是因为您正在传递一个分配给name变量的实例对象。你要做的:

def open_account(person) 
    puts "#{person.name}, thanks for opening an account at #{bank_name}!" 
end 

或者:

wells_fargo.open_account(friend1.name) 
+0

非常感谢,谢谢! – 2014-11-25 14:15:08

0

这里要传递的Person一个实例,而不是字符串。

chase.open_account(me) 

你必须要么通过me.name或修改open_account方法调用Person#name这样

def open_account(person) 
    puts "#{person.name}, thanks for opening an account at #{bank_name}!" 
end 
+0

非常感谢,谢谢! – 2014-11-25 14:15:29

0

你传递一个对象到open_account方法

你需要做的

def open_account(person) 
    puts "#{person.name}, thanks for opening an account at #{bank_name}!" 
end