Calling attr_accessor defines getters and setter for the *instances* of
the class, not the class itself. I'm also pretty sure that you want in
an class instance variable and not a class variable. Then you can simply
call attr_accessor in the singleton class of Test:
class Test @fields = 'ok'
class << self
attr_accessor :fields
end
end
p Test.fields
If you actually do want a class variable (and know what you're doing),
you have to define the getters and setters by hand. There's is no
ready-made method for this:
class Test
@@fields = 'ok'
def self.fields
@@fields
end
end
Thanks Jan,
Its great to hear such a complete and to the point answer, thank you
again. People like you gives me confidence that, one day I can also be
an expert of ruby!
You still should remove class variables from your repertoire. Their
scoping semantics is weird and - as this thread shows - they are not
very well integrated. Better leave them alone.
$ cat /tmp/cv.rb
class B1; (@@x ||= ) << 1; end
class D1 < B1; (@@x ||= ) << 2; end
class B1; printf "B1 %12d: %p\n", @@x.object_id, @@x end
class D1; printf "D1 %12d: %p\n", @@x.object_id, @@x end
class B2; end
class D2 < B2; (@@x ||= ) << 2; end
class D2; printf "D2 %12d: %p\n", @@x.object_id, @@x end
class B2; (@@x ||= ) << 1; end
class B2; printf "B2 %12d: %p\n", @@x.object_id, @@x end
class D2; printf "D2 %12d: %p\n", @@x.object_id, @@x end
Kind regards
robert
···
On Fri, Oct 5, 2012 at 8:03 AM, ajay paswan <lists@ruby-forum.com> wrote:
Thanks Jan,
Its great to hear such a complete and to the point answer, thank you
again. People like you gives me confidence that, one day I can also be
an expert of ruby!