Ruby:如何制作公共静态方法?

编程入门 行业动态 更新时间:2024-10-24 12:25:53
本文介绍了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:如何制作公共静态方法?

本文发布于:2023-07-15 10:22:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1110639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!