Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 837
user2309843 Avatar asked Jul 26 '26 02:07

user2309843


1 Answers

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)

like image 104
yzalavin Avatar answered Jul 28 '26 19:07

yzalavin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!