如何在ruby中定义私有方法?

Gir*_*iri 3 ruby ruby-on-rails

我是一名PHP程序员。刚开始学习Ruby。我对红宝石的私人声明感到困惑。

可以说我有这样的代码

private
def greeting
  random_response :greeting
end

def farewell
  radnom_response :farewell
end
Run Code Online (Sandbox Code Playgroud)

私人只适用于问候语还是问候语和告别?

Sir*_*sen 8

在 Ruby 2.1 中,方法定义返回其名称,因此您可以调用private传递函数定义的类。您还可以将方法名称传递给private. 之后定义的任何private不带任何参数的方法都将是私有方法。

这使您可以使用三种不同的方法来声明私有方法:

class MyClass
  def public_method
  end

  private def private_method
  end

  def other_private_method
  end
  private :other_private_method

  private
  def third_private_method
  end
end
Run Code Online (Sandbox Code Playgroud)


nzi*_*nab 6

将私有/受保护的方法放在文件底部是相当标准的。之后的所有内容都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
Run Code Online (Sandbox Code Playgroud)

如本例所示,如果确实需要,可以使用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
Run Code Online (Sandbox Code Playgroud)

使用private模块方法仅将单个方法声明为私有方法,但是坦率地说,除非您总是在每次方法声明后立即执行此操作,否则查找私有方法可能会有点混乱。我只喜欢将它们放在底部:)