调用自身方法的正确 Ruby 约定

Proper Ruby Convention for Calling Self Methods

我有一个关于命名约定的问题。在下面的示例中,我有一个要包含的模块,但只希望可以访问 top 函数。我使用 self 来实现这一点,但我想知道在每个 self 函数之前调用 self 是否合适,或者我是否可以排除它?

module MyMod
  def call_all_functions
    first_function # should this be self.first_function?
    second_function # should this be self.second_function?
  end

  def self.first_function
  end

  def self.second_function
  end
end

如果您只想在项目的其他地方使用第一个函数,您可以执行以下操作:

module MyMod
  def self.call_all_functions
    first_function
    second_function
  end

  def first_function
  end

  def second_function
  end
end

如果您不打算再次使用 first_functionsecond_function,最好这样做:

module MyMod
  def self.call_all_functions
    first_function
    second_function
  end

private

  def first_function
  end

  def second_function
  end
end

private 在这里所做的是使这些功能只能由这个文件访问。