类<<Ruby 的 self 与 self.method:哪个更好? [英] class << self vs self.method with Ruby: what's better?
问题描述
这个 Ruby 风格指南 告诉我们最好使用 self.method_name
class method_name
.但为什么?
This Ruby Style Guide tells that is better using self.method_name
instead of class method_name
. But Why?
class TestClass
# bad
class << self
def first_method
# body omitted
end
def second_method_etc
# body omitted
end
end
# good
def self.first_method
# body omitted
end
def self.second_method_etc
# body omitted
end
end
是否存在性能问题?
推荐答案
class <<self
擅长将所有类方法保存在同一个块中.如果以 def self.method
形式添加方法,则不能保证(除了约定俗成和一厢情愿)不会在文件后面隐藏额外的类方法.
class << self
is good at keeping all of your class methods in the same block. If methods are being added in def self.method
form then there's no guarantee (other than convention and wishful thinking) that there won't be an extra class method tucked away later in the file.
def self.method
擅长明确声明一个方法是一个类方法,而 class <<<;self
你必须自己去找容器.
def self.method
is good at explicitly stating that a method is a class method, whereas with class << self
you have to go and find the container yourself.
其中哪一个对您更重要是一个主观决定,还取决于其他人在编写代码以及他们的偏好等因素.
Which of these is more important to you is a subjective decision, and also depends on things like how many other people are working on the code and what their preferences are.
这篇关于类<<Ruby 的 self 与 self.method:哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!