Forum: Ruby Unable to work with class variable

Posted by Prog Rammer (proggrammer)
on 2012-10-04 15:37
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 by Jan E. (jacques1)
on 2012-10-04 15:44
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 a 
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 by Prog Rammer (proggrammer)
on 2012-10-05 08:03
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 by Robert Klemme (robert_k78)
on 2012-10-05 18:46
(Received via mailing list)
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!

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
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.