Sun*_*aek 5 ruby variables interpolation
如果我有如下变量,
i = 1
k1 = 20
Run Code Online (Sandbox Code Playgroud)
有什么方法可以通过 i 的插值获得 k1 的值吗?
就像是,
k"#{i}"
=> 20
Run Code Online (Sandbox Code Playgroud)
提前致谢。
这取决于它是局部变量还是方法。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"
Run Code Online (Sandbox Code Playgroud)
如果确实需要,您可以使用 currentBinding和访问局部变量local_variable_get:
i = 1
k1 = "one"
local_variables
# => [:i, :k1]
binding.local_variable_get("k#{i}")
# => "one"
Run Code Online (Sandbox Code Playgroud)
但这非常糟糕。在这种情况下,你最好使用Hash:
i = 1
k = {1 => "one"}
k[i]
# => "one"
Run Code Online (Sandbox Code Playgroud)