I thought I opened the object so I could add instance variables to it,
but I guess this should be done like
my_inst.instance_variable_set(...)
or can this be done like I'm trying ?
There's a very simple rule: every time you see this:
@var
you are seeing an instance variable that belongs to 'self' -- that is,
whatever 'self' happens to be at the time.
Your example looks like this:
class C
end
c = C.new
class << c
@x = 1
end
If you check for self at that point in execution, you'll find that
self is the class you've just opened up -- namely, the singleton class
of the object c:
class << c
p self # #<Class:#<C:0x7aeb8>>
end
So the instance variable defined at that point belongs to the class.
It's not specific to singleton classes; it's about self.
class C
@x = 1 # belongs to the class object C
def instance_x
@x # belongs to whatever instance of C is 'self'
end
end