object singleton problem

Hi All

I'm trying to add an instance variable and a method to a object
The CODE:

#! /usr/bin/ruby

class Xyz
def initialize
   p "initializing"
end
end

my_inst = Xyz.new

class <<my_inst
  @new_var = "Hello world"

  def get_new_var
    p "instance method"
    @new_var
  end
end

p my_inst.get_new_var
# =========

prints:
instance method
nil

Any suggestions why the variable is 'nil' ??

Thnx a lot
LuCa

@new_var is a Class attribute only accessible in class methods.

check this out:

http://ghouston.blogspot.com/2006/06/ruby-class-variables-attributes-and.html

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 ?

Hi --

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

David

thnx, but how would I access the @x variable which belongs to the class
object C ?

Hi --

thnx, but how would I access the @x variable which belongs to the class
object C ?

Like any object, C can expose its instance variable through accessor
methods:

   class << C
     attr_accessor :x
   end

   C.x = 1 # etc.

You can also use instance_eval or instance_variable_get, but those are
"impolite" ways of making an object show you its data. (Useful, but
impolite :slight_smile:

David

my examples uses an object not the class, so if I would do

   obj = Xyz.new

   class << obj
     attr_accessor :x
   end

how would I assign a value to x and how would I retrieve it ?

thnx a lot

Hi --