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's the equivalent 'Ruby way' of writing a 'static method'?
Methods may be public, private, or protected, but there is no concept of a static method or variable in Ruby. Ruby doesn't have a static keyword that denotes that a particular method belongs to the class level.
A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it.
To declare a static variable, we just need to declare a class variable that will act as a static one, as it will be common to all the instances of the class. In simple terms, when we talk about Ruby, the static variables are declared using the class variable.
A non-static method does not have the keyword static before the name of the method. A non-static method belongs to an object of the class and you have to create an instance of the class to access it. Non-static methods can access any static method and any static variable without creating an instance of the class.
Use self:
class Horse
def self.say
puts "I said moo."
end
end
Horse.say
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With