Search code examples
rubyclasssetterinstance-variables

Ruby - set instance variable inside class method from string


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!


Solution

  • 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)