Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a Java static method look like in Ruby?

Tags:

java

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's the equivalent 'Ruby way' of writing a 'static method'?

like image 307
Hosh Avatar asked Mar 17 '10 05:03

Hosh


People also ask

Are there static methods in Ruby?

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.

How do you identify a static method?

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.

How do you define a static variable in Ruby?

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.

What does Nonstatic mean in Java?

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.


1 Answers

Use self:

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

Horse.say
like image 182
aoj Avatar answered Oct 22 '22 09:10

aoj