Reputation: 243
I have a class with a method register(key, val)
. I am trying to add key
as a instance variable of the class and set it equal to val
. Right now I'm trying to use self.instance_variable_set(':@' + key, val)
but I'm getting this error:
in `instance_variable_set': `:@table' is not allowed as an instance variable name (NameError)
I am calling register('table', {'key' => 'value'})
Any idea how to do this properly? Thanks!
Upvotes: 3
Views: 2549
Reputation: 1836
Remove :
from your method.
self.instance_variable_set('@' + key, val)
Moreover, self
can be redundant here. Try instance_variable_set('@' + key, val)
.
And prefer to use interpolation over concatenation. instance_variable_set("@#{key}", val)
Upvotes: 6