Where to place private methods in Ruby?
The best practice in my point of view is to go sequentially and declare your methods without keeping private in point of view.
At the end, you can make make any method private by just adding: private :xmethod
Example:
class Example def xmethod end def ymethod end def zmethod end private :xmethod, :zmethodend
Does this justify your question?
There's also the option to prepend private
to the method definition since Ruby 2.1.
class Example def xmethod end private def ymethod end private def zmethod endend
Looking at the definition, you instantly know if a method is private, no matter where in the file it's defined. It's a bit more typing (if you don't autocomplete) and not all your def
s will be nicely aligned.
As others have already pointed out the convention is to put private methods at the bottom, under one private class. However, you should probably also know that many programers use a double indented (4 spaces instead of 2) method for this. The reason is that often times you won't see "private" in your text editor and assume they could be public. See below for an illustration:
class FooBar def some_public_method end def another_public_method endprivate def some_private_method end def another_private method endend
This method should prevent you from having to scroll up and down and will make other programmers more comfortable in your code.