加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby静态方法在Ruby中是什么样的?

发布时间:2020-12-16 20:49:53 所属栏目:百科 来源:网络整理
导读:在Java中,’静态方法’看起来像这样: class MyUtils { . . . public static double mean(int[] p) { int sum = 0; // sum of all the elements for (int i=0; ip.length; i++) { sum += p[i]; } return ((double)sum) / p.length; } . . .}// Called from o
在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方式”是什么?

解决方法

Anders的回答是正确的,但是对于像你不需要使用类的实用方法,你可以把方法放在 module中:
module MyUtils
  def self.mean(values)
    # implementation goes here
  end
end

该方法将以相同的方式调用:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读