Ruby:如何制作公共静态方法? [英] Ruby: How to make a public static method?

查看:35
本文介绍了Ruby:如何制作公共静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中我可能会这样做:

In Java I might do:

public static void doSomething();

然后我可以在不创建实例的情况下静态访问该方法:

And then I can access the method statically without making an instance:

className.doSomething(); 

我怎样才能在 Ruby 中做到这一点?这是我的课程,根据我的理解 self. 使方法静态:

How can I do that in Ruby? this is my class and from my understanding self. makes the method static:

class Ask

  def self.make_permalink(phrase)
    phrase.strip.downcase.gsub! /\ +/, '-'
  end

end

但是当我尝试打电话时:

But when i try to call:

Ask.make_permalink("make a slug out of this line")

我明白了:

undefined method `make_permalink' for Ask:Class

如果我没有将方法声明为私有,为什么会这样?

Why is that if i haven't declared the method to be private?

推荐答案

您给出的示例运行良好

class Ask
  def self.make_permalink(phrase)
    phrase.strip.downcase.gsub! /\ +/, '-'
  end
end

Ask.make_permalink("make a slug out of this line")

我在 1.8.7 和 1.9.3 中都尝试过您的原始脚本中是否有错别字?

I tried in 1.8.7 and also in 1.9.3 Do you have a typo in you original script?

一切顺利

这篇关于Ruby:如何制作公共静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆