Ruby静态方法在Ruby中是什么样的?
在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);
编写“静态方法”的等效“Ruby方式”是什么?
Anders的回答是正确的,但是对于像你不需要使用类的实用方法,你可以把方法放在一个模块中 :
module MyUtils def self.mean(values) # implementation goes here end end
该方法将以相同的方式调用:
avg = MyUtils.mean([1,2,3,4,5])
使用自我:
class Horse def self.say puts "I said moo." end end Horse.say