Attr_accessor on class variables

ruby

Solution

`attr_accessor` defines accessor methods for an instance. If you want class level auto-generated accessors you could use it on the metaclass

class Parent
  @things = []

  class << self
    attr_accessor :things
  end
end

Parent.things #=> []
Parent.things << :car
Parent.things #=> [:car]

but note that this creates a class level instance variable not a class variable. This is likely what you want anyway, as class variables behave differently than you might expect when dealing w/ inheritance. See "Class and Instance Variables In Ruby".

Problem

`attr_accessor` does not work on the following code. The error says "`undefined method 'things' for Parent:Class (NoMethodError)`": ``` class Parent @@things = [] attr_accessor :things end Parent.things << :car p Parent.things ``` However the following code works ``` class Parent @@things = [] def self.things @@things end def things @@things end end Parent.things << :car p Parent.things ```

Original source

Related problems