How to Create a "Static" Class Method in Ruby?

A static method in Ruby is called a class method. You can create a class method by defining the method on "self" (which refers to the class itself), for example, like so:

class Foo
    def self.bar
        "bar"
    end
end

puts Foo.bar #=> "bar"

You can also use the class name itself instead of self (as the two are equivalent):

class Foo
    def Foo.bar
        "bar"
    end
end

puts Foo.bar #=> "bar"

You could also use the name of an already existing class to define a static/class method on it, for example, like so:

class Foo
    # ...
end

def Foo.bar
  "bar"
end

puts Foo.baz #=> "bar"

If you need to define multiple static/class methods, then you can define them inside a static block (i.e. within "class << self"), for example, like so:

class Foo
    class << self
        def bar
            "bar"
        end

        def baz
            "baz"
        end
    end
end

puts Foo.bar #=> "bar"
puts Foo.baz #=> "baz"

In this way, you don't have to prefix each static/class method with "self".


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.