我有以下代码:
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的名称。我已经阅读了很多关于类/实例变量的内容,但似乎无法弄明白。
答案 0 :(得分:2)
这是因为您传递的是分配给name变量的实例对象。你必须这样做:
def open_account(person)
puts "#{person.name}, thanks for opening an account at #{bank_name}!"
end
或者:
wells_fargo.open_account(friend1.name)
答案 1 :(得分: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
答案 2 :(得分:0)
将对象传递给open_account方法
你需要做
def open_account(person)
puts "#{person.name}, thanks for opening an account at #{bank_name}!"
end