2014-11-25 31 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