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?
Inside your
instancemethod, the parameterinscontains the name of the variable, not its value. As written, there’s no way to get at its value from that point.If you call
instancefrom 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:Which would work like this: