3

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!

4
  • 1
    @DaveNewton that is a confusing statement. Commented Jun 14, 2017 at 16:16
  • @DaveNewton "it's not a class method if you're referencing self" this makes very little sense to me. self can reference a Class just as it can reference an instance of a Class and if we are being technical about this all methods are instance_methods because everything is an instance. Commented Jun 14, 2017 at 16:39
  • Just out of curiosity: is the error message really that hard to understand? Can you give any hints as to how it could be improved for future readers? Commented Jun 15, 2017 at 0:16
  • I'm really new to Ruby, so I didn't know what the solution was. In hindsight, the error message made perfect sense. Commented Jun 15, 2017 at 14:00

1 Answer 1

6

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)

Sign up to request clarification or add additional context in comments.

3 Comments

I tried the interpolation method and it works with double quotes but not single quotes, do you know why that is?
@achang27 it's because, well ... string interpolation works within double quotes but not within single quotes. That's the way string literals work in Ruby.
Regarding : – if you want to pass the instance variable's name as a symbol (as shown in the docs), the syntax is :"@#{key}". With key = 'table', it returns the symbol :@table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.