简体   繁体   中英

What does a Java static method look like in Ruby?

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

class MyUtils {
    . . .
    public static double mean(int[] p) {
        int sum = 0;  // sum of all the elements
        for (int i=0; i<p.length; i++) {
            sum += p[i];
        }
        return ((double)sum) / p.length;
    }
    . . .
}

// Called from outside the MyUtils class.
double meanAttendance = MyUtils.mean(attendance);

What's the equivalent 'Ruby way' of writing a 'static method'?

Use self:

class Horse
  def self.say
    puts "I said moo."
  end
end

Horse.say

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM