How to define a private method in Ruby?

ruby, ruby-on-rails

Solution

It's fairly standard to put private/protected methods at the bottom of the file. Everything after `private` will become a private method.

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

As you can see in this example, if you really need to you can go back to declaring public methods by using the `public` keyword.

It can also be easier to see where the scope changes by indenting your private/public methods another level, to see visually that they are grouped under the `private` section etc.

You also have the option to only declare one-off private methods like this:

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

Using the `private` module method to declare only single methods as private, but frankly unless you're always doing it right after each method declaration it can be a bit confusing that way to find the private methods. I just prefer to stick them at the bottom :)

Problem

Just started to learn Ruby. I'm confused with Ruby's `private` keyword. Let's say I have code like this ``` private def greeting random_response :greeting end def farewell random_response :farewell end ``` Does `private` only applied to the `#greeting` or both - `#greeting` and `#farewell`?

Original source