Sunki Baek Sunki Baek - 23 days ago 7
Ruby Question

Ruby, using interpolation in variables' names

If I have variables as below,

i = 1
k1 = 20


is there any ways to get values of k1 with the interpolation of i?

Something like,

k"#{i}"
=> 20


Thanks in advance.

Answer

It depends on whether it's a local variable or a method. send "k#{i}" should do the trick with methods:

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"

If you really need to, you can access local variables using the current Binding and local_variable_get:

i = 1
k1 = "one"
local_variables
# => [:i, :k1]
binding.local_variable_get("k#{i}")
# => "one"

This is pretty awful though. In this instance you'd be better off using a Hash:

i = 1
k = {1 => "one"}
k[i]
# => "one"