From: dblack@... Date: 2006-10-23T20:23:10+09:00 Subject: Re: newbie: class attribute accessors? Hi -- On Mon, 23 Oct 2006, Diego Virasoro wrote: >> Please explain. Use an example. > > From what I understood, for any instance variable, I can make ruby > automatically produce the accessors. For example: > > class Dog > @name > @@NumberOfLegs = 4 > > attr_accessor :name > end > > x = Animal.new > ... > puts x.name > > > However, I would like to do something similar for class variables. So > for example in the above example, for @@NumberOfLegs. > > Is this possible? See Farrel's answer; you can write wrapper methods. Note, however, that these are not exactly "attributes". Class variables are shared among many different objects (all the classes in a hierarchy; all the instances of all those classes), so they can't represent an attribute in the normal/usual sense. You can certainly give your class objects attributes. Just call attr_accessor in the object's singleton class: class Dog class << self attr_accessor :number_of_legs end self.number_of_legs = 4 end puts Dog.number_of_legs # => 4 Dog.number_of_legs = 10 # well, maybe attr_reader is better :-) David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org