What does a static Java 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 is the equivalent of the "Ruby way" for writing a "static method"?

+6
java ruby
source share
2 answers

Anders' answer is correct, however for utility methods such as mean you do not need to use a class, you can put this method in module :

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

The method will be called in the same way:

 avg = MyUtils.mean([1,2,3,4,5]) 
+5
source share

Use self:

 class Horse def self.say puts "I said moo." end end Horse.say 
+10
source share

All Articles