Unable to work with class variable

Here is my code:
class Test
  @@fields="ok"

  attr_accessor :fields

  #initialize attributes.
  def initialize()
  end
end
a= Test.fields

It says:
test.rb:11: undefined method `fields' for Test:Class (NoMethodError)

Why? even I have mentioned attr_accessor.

···

--
Posted via http://www.ruby-forum.com/.

Hi,

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

p Test.fields

···

--
Posted via http://www.ruby-forum.com/.

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!

···

--
Posted via http://www.ruby-forum.com/.

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.

Example for the weird scoping:

$ ruby /tmp/cv.rb
B1 -1072888598: [1, 2]
D1 -1072888598: [1, 2]
D2 -1072888848: [2]
B2 -1072888918: [1]
D2 -1072888918: [1]

$ 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!

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/