Where to place private methods in Ruby?

Most of the blogs or tutorials or books have private methods at the bottom of any class/module. Is this the best practice?

I find having private methods as and when necessary more convenient. For example:

public
def my_method
  # do something
  minion_method
end

private
def minion_method
  # do something
end

public
def next_method
end

This way I find the code more readable instead of scrolling up and down continuously which is very irritating.

Is there something terribly wrong in this approach? Is having private methods at the bottom not just a best practice and something else?


Solution 1:

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, :zmethod

end

Does this justify your question?

Solution 2:

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_class_method def self.zmethod 
 end
end

You can instantly see if a method is private, no matter where in the (large) file it is. And it's consistent with many other languages. But it's a bit more typing and doesn't nicely align.