Ruby - 在 class 方法中从字符串设置实例变量

Ruby - set instance variable inside class method from string

我有一个 class 方法 register(key, val)。我正在尝试添加 key 作为 class 的实例变量并将其设置为等于 val。现在我正在尝试使用 self.instance_variable_set(':@' + key, val) 但我收到此错误:

in `instance_variable_set': `:@table' is not allowed as an instance variable name (NameError)

我正在打电话register('table', {'key' => 'value'})

知道如何正确地做到这一点吗?谢谢!

从您的方法中删除 :

self.instance_variable_set('@' + key, val)

此外,self在这里可以是多余的。试试 instance_variable_set('@' + key, val).

并且更喜欢使用插值而不是串联。 instance_variable_set("@#{key}", val)