What you are doing is defining an instance variable at the class level (since classes are instances of the Class class, this works just fine).
And no, there is no way to initialize.
Edit: You have a slight misconception in your editing. attr_accessor
does not add an instance variable to the class. Literally, this happens (using your my
example):
def my; @my; end def my=(value); @my = value; end
It does not actively create / initialize any instance variable; it simply defines two methods. And you can well write your own class method that does similar things using define_method
.
Edit 2:
To illustrate how to write such a method:
class Module def array_attr_accessor(name) define_method(name) do if instance_variable_defined?("@#{name}") instance_variable_get("@#{name}") else instance_variable_set("@#{name}", []) end end define_method("#{name}=") do |val| instance_variable_set("@#{name}", val) end end end class Test array_attr_accessor :my end t = Test.new t.my
source share