Ruby,在变量名称中使用插值

时间:2012-04-17 01:15:56

标签: ruby variables interpolation

如果我有如下变量,

i = 1
k1 = 20

有没有办法用i?

的插值得到k1的值

类似的东西,

k"#{i}"
=> 20

提前致谢。

1 个答案:

答案 0 :(得分:4)

取决于它是local variable还是methodsend "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"

如果确实需要,可以使用当前Bindinglocal_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"