如何设置此代码设置实例变量的值?

时间:2022-10-07 13:16:29

I have the following code, meant to turn a normal variable into an instance variable.

我有以下代码,意味着将正常变量转换为实例变量。

BasicObject.class_eval do
    def instance(ins)
        self.instance_variable_set("@#{ins}", ins)
    end
end

Lets say the user says

让我们说用户说

class X
  foo = 3
end
bar = X.new
bar.instance(:foo)

What I want it to do is set the new created variable, @foo to 3, instead, it sets @foo to :foo. How do I make the code do what I want?

我想要它做的是将新创建的变量@foo设置为3,而是将@foo设置为:foo。如何使代码完成我想要的?

1 个解决方案

#1


1  

Inside your instance method, the parameter ins contains the name of the variable, not its value. As written, there's no way to get at its value from that point.

在实例方法中,参数ins包含变量的名称,而不是其值。如上所述,从那时起就没有办法达到它的价值。

If you call instance from a point in the code where the source variable is actually visible, which it's not in your example (see my comment above), you can also pass the local variable binding, and then use that. Something like this:

如果从源代码实际可见的代码中的某个点调用实例,这不在您的示例中(请参阅上面的注释),您也可以传递局部变量绑定,然后使用它。像这样的东西:

def instance(var, bound)
    eval "@#{var}=#{var}", bound
end

Which would work like this:

哪个会像这样工作:

foo = 3
instance('foo', binding)
@foo   # => 3

#1


1  

Inside your instance method, the parameter ins contains the name of the variable, not its value. As written, there's no way to get at its value from that point.

在实例方法中,参数ins包含变量的名称,而不是其值。如上所述,从那时起就没有办法达到它的价值。

If you call instance from a point in the code where the source variable is actually visible, which it's not in your example (see my comment above), you can also pass the local variable binding, and then use that. Something like this:

如果从源代码实际可见的代码中的某个点调用实例,这不在您的示例中(请参阅上面的注释),您也可以传递局部变量绑定,然后使用它。像这样的东西:

def instance(var, bound)
    eval "@#{var}=#{var}", bound
end

Which would work like this:

哪个会像这样工作:

foo = 3
instance('foo', binding)
@foo   # => 3