在Ruby中将私有方法放在哪里? [英] Where to place private methods in Ruby?

查看:97
本文介绍了在Ruby中将私有方法放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数博客,教程或书籍在任何类/模块的底部都有私有方法。这是最佳做法吗?

Most of the blogs or tutorials or books have private methods at the bottom of any class/module. Is this the best practice?

我发现在需要时使用私有方法更为方便。例如:

I find having private methods as and when necessary more convenient. For example:

public
def my_method
  # do something
  minion_method
end

private
def minion_method
  # do something
end

public
def next_method
end

这样,我发现代码更具可读性,而不是不断地上下滚动,这很烦人。

This way I find the code more readable instead of scrolling up and down continuously which is very irritating.

这种方法是否存在严重错误?

Is there something terribly wrong in this approach? Is having private methods at the bottom not just a best practice and something else?

推荐答案

在我看来,最好的做法是在底部使用私有方法吗?

The best practice in my point of view is to go sequentially and declare your methods without keeping private in point of view.

最后,您只需添加以下内容即可将任何方法设为私有: private:xmethod

At the end, you can make make any method private by just adding: private :xmethod

示例:

class Example
 def xmethod
 end

 def ymethod
 end

 def zmethod 
 end

 private :xmethod, :zmethod

end

这是否合理您的问题?

这篇关于在Ruby中将私有方法放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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