我是一名PHP程序员。刚开始学习Ruby。我对红宝石的私人声明感到困惑。
可以说我有这样的代码
private
def greeting
random_response :greeting
end
def farewell
radnom_response :farewell
end
私人只适用于问候语还是问候语和告别?
将私有/受保护的方法放在文件底部是相当标准的。之后的所有内容都private
将成为私有方法。
class MyClass
def a_public_method
end
private
def a_private_method
end
def another_private_method
end
protected
def a_protected_method
end
public
def another_public_method
end
end
如本例所示,如果确实需要,可以使用public
关键字返回声明公共方法。
通过将您的私有/公共方法缩进另一层,直观地看到它们被分组在该private
部分下,还可以更容易地看到范围的变化。
您还可以选择仅声明一次性私有方法,如下所示:
class MyClass
def a_public_method
end
def a_private_method
end
def another_private_method
end
private :a_private_method, :another_private_method
end
使用private
模块方法仅将单个方法声明为私有方法,但是坦率地说,除非您总是在每次方法声明之后立即执行此操作,否则这种查找私有方法的方法会有些混乱。我只喜欢将它们放在底部:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句