如果我有如下变量,
i = 1
k1 = 20
有没有办法用i?
的插值得到k1的值类似的东西,
k"#{i}"
=> 20
提前致谢。
答案 0 :(得分:4)
取决于它是local variable还是method。 send "k#{i}"
应该使用方法:
class Foo
attr_accessor :i, :k1
def get
send "k#{i}"
end
end
foo = Foo.new
foo.i = 1
foo.k1 = "one"
foo.get
# => "one"
如果确实需要,可以使用当前Binding
和local_variable_get
访问本地变量:
i = 1
k1 = "one"
local_variables
# => [:i, :k1]
binding.local_variable_get("k#{i}")
# => "one"
但这非常糟糕。在这种情况下,您最好使用Hash
:
i = 1
k = {1 => "one"}
k[i]
# => "one"