我在论坛上提到了这个问题: Using a string as a variable at run time
这就是我所拥有的:
def create_account
puts "Username?"
account_name=gets.chomp
account_name_var=#account_name as variable
#Sets array as variable
string_values = { }
some_string = [:some_string] # parameter was, say "Hello"
string_values[some_string] = account_name
string_values # { 'Hello' => 42 }
account_name_var = string_values[some_string]
account_name_var # 42
account_name_var=BankAccount.new(account_name, "open")
account_name_var=BankAccount.new(account_name, "open")
end
create_account
create_account
# pablo=BankAccount.new("pablo", "open")
# theo=BankAccount.new("theo", "open")
make_transfer(name, name2, 10)
但是我得到了
:main:Object的未定义局部变量或方法名称 make_transfer(name,name2,10)
行上的(NameError)
当我输入name
作为第一个用户名并name
作为第二个用户名时,name2
未设置为变量。
答案 0 :(得分:2)
只需从您的方法返回BankAccount
实例并将其分配给变量:
def create_account
puts "Username?"
account_name = gets.chomp
BankAccount.new(account_name, "open")
end
account_1 = create_account
account_2 = create_account
make_transfer(account_1, account_2, 10)
或者,使用Hash
按名称存储帐户:
@accounts = {}
account = create_account
@accounts[account.name] = account
account = create_account
@accounts[account.name] = account
make_transfer(@accounts['pablo'], @accounts['theo'], 10)