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

Find out how to make a static method in a Ruby class

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".


Hope you found this post useful. It was published . Please show your love and support by sharing this post.