The Data Asylum

Programming, Databases and People

Creating a Static Class Variable in Ruby

One of the patterns I (over)use in php is having a class with only static variables and static functions. To do this in ruby isn’t as straight forward as it could be, so here is how to do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class StaticKlass

    # ruby class variables are prefixed with '@@' .
    @@variable = nil

    # If you want to provide getters and setters you cant use the attr_accessor
    # keyword, you have to create them manually. By adding the class name to
    # the method definition, we are indicating that this is a method on the
    # class, not in instances of this class
    def StaticKlass.variable= (x)
        @@variable = x
    end

    # the getter is defined to return the class variable when called
    def StaticKlass.variable
        return @@variable
    end

end

Comments