Ruby- attr_accessor for Class Variables


Here’s how you do it:

class Foo
    class << self
	# Everything here is in class scope
        attr_accessor :bar
    end
end

That’s it. What class << self does is, it puts you in a class definition block for the singleton Class instance of Foo. Lets make that a bit clearer with an example. The following two snippets are functionally identical:

class Foo
    def self.bar
        42
    end
end

is the same as

class Foo
    class << self
        def bar
            42
        end
    end
end

Sometimes I wonder why other languages aren’t as elegant as Ruby. But then again, it’s somewhat difficult to get your head wrapped around some of the meta-programming concepts of Ruby, too.

Thanks to these guys for the solution.