Ruby: How to make a public static method?

前端 未结 4 1863
醉梦人生
醉梦人生 2021-02-01 12:15

In Java I might do:

public static void doSomething();

And then I can access the method statically without making an instance:

c         


        
4条回答
  •  伪装坚强ぢ
    2021-02-01 12:38

    There is one more syntax which is has the benefit that you can add more static methods

    class TestClass
    
      # all methods in this block are static
      class << self
        def first_method
          # body omitted
        end
    
        def second_method_etc
          # body omitted
        end
      end
    
      # more typing because of the self. but much clear that the method is static
      def self.first_method
        # body omitted
      end
    
      def self.second_method_etc
        # body omitted
      end
    end
    

提交回复
热议问题