Code tips #6: Ruby – The clear way to declare static methods in a Class

In Ruby to define a static method in a Class, you can write the following:

class Song
  def Song.start
    p "Music start...!"
  end

  def Song.stop
    p "Music stop!"
  end
end

This works fine but in every function definition, you have to retype the name of the class, meaning that in case you decide to rename the Class you have to change all of these method names. A better solution would be

to use “self”:

class Song
  def self.start
    p "Music start...!"
  end

  def self.stop
    p "Music stop!"
  end
end

Another way to achieve the same, without having to type self for every function name, but is less clear in my opinion is the following:

class Song
  class << self
    def start
      p "Music start...!"
    end

    def stop
      p "Music stop!"
    end
  end
end

Leave a Reply

Your email address will not be published. Required fields are marked *