在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)
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)
| 归档时间: |
|
| 查看次数: |
1849 次 |
| 最近记录: |