2010-03-17 60 views
6

在Java中,一個「靜態方法」應該是這樣的: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的方式」?

回答

5

Anders的答案是正確的,但是對於像mean你不需要使用類的實用方法,你可以把方法在module

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

該方法會以同樣的方式被稱爲:

avg = MyUtils.mean([1,2,3,4,5]) 
10

使用自:

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

Horse.say 
+4

哇從來沒有遇到一個馬說哞:P – 2010-03-17 05:31:54

+3

這是一個非常特殊的馬:) – aoj 2010-03-17 05:33:59

+0

@Nathan W:我以爲[馬](http://en.wikipedia.org/wiki/Footrot_Flats#Main_characters)去了miaow。 – 2011-01-27 22:16:28