2015-07-13 141 views
1

我都提到了這個問題,在論壇上這樣做: Using a string as a variable at run time爲什麼我不能轉換的inputed字符串到變量

這是我有:

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) 

,但我得到

:用於主未定義局部變量或方法名稱:對象 (NameError)就行了make_transfer(姓名,NAME2 10)

因此,當我輸入name作爲第一個用戶名和name2作爲第二個用戶名時,name未被設置爲變量。

+3

如果你輸入什麼'foobar的'作爲第一個用戶名?你是否期望代碼文件奇蹟般地改變以反映這種意想不到的輸入? –

回答

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) 
相關問題