2010-01-30 57 views

回答

7

可以使用eval

x = "myvar" 
myvar = "hi" 
eval(x) -> "hi" 
5

這可能僅適用於實例變量(和類變量)實現類似的東西:

class MyClass 
    def initialize 
    @varname = :"@hello" 
    instance_variable_set @varname, "world" 
    end 

    def greet 
    puts instance_variable_get(@varname) 
    end 
end 

MyClass.new.greet 
#=> "world" 

對於必須使用eval局部變量。

+0

第3行有沒有額外的冒號? – btelles 2010-01-30 17:30:02

+0

是的,冒號等同於在字符串文字上調用to_sym:將其轉換爲符號。 – molf 2010-01-30 17:36:12

+0

IOW':「abcdef」==「abcdef」.to_sym ==:abcdef',您也可以使用插值法:「#{klazz} _#{id}」==「#{klazz} _#{id }」。to_sym'。 – yfeldblum 2010-01-30 17:56:00

相關問題