Ruby, using interpolation in variables' names
interpolation, ruby, variables
Solution
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"
Problem
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.