如果我有如下变量,
i = 1
k1 = 20
有什么方法可以通过 i 的插值得到 k1 的值吗?
有点像,
k"#{i}"
=> 20
提前致谢。
最佳答案
这取决于它是否是 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"
关于Ruby,在变量名称中使用插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10183808/