Singeton class and Instance variable

class Foo
class<< self
@foo=100;
end
end
Here @foo is it a instance variable or class variable and how to access
the value of @foo?
I tried Foo.instance_variables it was nil,same with Foo.class_variables
it was nil.

Hello!

In your example ‘@foo’ is not a class variable (class variables use the
@@ notation, notice the double @) or an instance variable of Foo.

What you want to do here is to move your @foo outside the “class <<
self” & also make sure you give it a value, because all instance
variables default to ‘nil’ (even if undefined).

Then you should be able to see it via:

‘Foo.instance_variables’

To access it you will need to define an accessor or use a
metaprogramming method like instance_eval.

Complete example:

class Foo
  @foo = 100

  class << self
    attr_reader :foo
  end
end

p Foo.foo

I hope that helps!

  • Jesus Castello

Thanks for the info.
I got it what you explained above.
Actually this question was asked in an interview what type of variable
is @foo is it a class variable or instance variable ?

In your example ‘@foo’ is an instance variable of Foo’s singleton class.

You can see this if you run the following code:

p Foo.singleton_class.instance_variables

Thanks for the info,one more query how to access singleton class
instance variables in ruby any idea?

If you have a new question, it is advisable to start a new thread.

Anyway: I guess you mean how to access them from outside of the class,
isn’t it? This is not different from non-singleton classes: You can’t.
What you can do, is to provide a method for accessing the variable, and
since this is such a common task, there are special methods called
attr_accessor, attr_reader and attr_writer in class Module - see for
instance here:

Since class Class inherits from Module, they are available in a
singleton class too.