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.
on 2016-11-09 14:07
on 2016-11-10 21:17
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
on 2016-11-11 18:30
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 ?
on 2016-11-11 19:40
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
on 2016-11-12 18:17
Thanks for the info,one more query how to access singleton class instance variables in ruby any idea?
on 2016-11-14 12:15
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: http://ruby-doc.org/core-1.9.3/Module.html#method-... Since class Class inherits from Module, they are available in a singleton class too.