Ruby静态方法在Ruby中看起来像什么?

Hos*_*osh 6 ruby java

在Java中,'静态方法'看起来像这样:

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);
Run Code Online (Sandbox Code Playgroud)

编写"静态方法"的等效"Ruby方式"是什么?

aoj*_*aoj 10

使用自己:

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

Horse.say
Run Code Online (Sandbox Code Playgroud)

  • 这是一匹非常特别的马:) (3认同)

mik*_*kej 5

Anders的回答是正确的,但是对于像mean不需要使用类的实用方法,可以将方法放在模块中:

module MyUtils
  def self.mean(values)
    # implementation goes here
  end
end
Run Code Online (Sandbox Code Playgroud)

该方法将以相同的方式调用:

avg = MyUtils.mean([1,2,3,4,5])
Run Code Online (Sandbox Code Playgroud)