Forum: Ruby Singeton class and Instance variable

0acd32d40707bf9a17e02deb31fb7b93?d=identicon&s=25 Etika A. (etika_a)
on 2016-11-09 14:07
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.
C2d1339038b5fec16b5b15878f648d96?d=identicon&s=25 Jesus Castello (jesus_castello)
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
0acd32d40707bf9a17e02deb31fb7b93?d=identicon&s=25 Etika A. (etika_a)
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 ?
C2d1339038b5fec16b5b15878f648d96?d=identicon&s=25 Jesus Castello (jesus_castello)
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
0acd32d40707bf9a17e02deb31fb7b93?d=identicon&s=25 Etika A. (etika_a)
on 2016-11-12 18:17
Thanks for the info,one more query how to access singleton class
instance variables in ruby  any idea?
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
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.
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.