What does a Java static method look like in Ruby?

前端 未结 2 1876
别跟我提以往
别跟我提以往 2020-12-20 19:14

In Java, a \'static method\' would look like this:

class MyUtils {
    . . .
    public static double mean(int[] p) {
        int sum = 0;  // sum of all the         


        
相关标签:
2条回答
  • 2020-12-20 19:54

    Anders' answer is correct, however for utility methods like mean you don't need to use a class, you can put the method in a module:

    module MyUtils
      def self.mean(values)
        # implementation goes here
      end
    end
    

    The method would be called in the same way:

    avg = MyUtils.mean([1,2,3,4,5])
    
    0 讨论(0)
  • 2020-12-20 20:14

    Use self:

    class Horse
      def self.say
        puts "I said moo."
      end
    end
    
    Horse.say
    
    0 讨论(0)
提交回复
热议问题