Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 306
ZX12R Avatar asked May 23 '12 16:05

ZX12R


People also ask

Where do you put private methods?

Martin advises coders to always put member variables at the top of the class (constants first, then private members) and methods should be ordered in such a way so that they read like a story that doesn't cause the reader to need to jump around the code too much.

How do you call a private method in Ruby?

Using BasicObject#instance_eval , you can call private method.

Why do we declare private methods Ruby?

What is a private method in Ruby? It's a type of method that you can ONLY call from inside the class where it's defined. This allows you to control access to your methods.

Can a Ruby module have private methods?

Private instance/class methods for modulesDefining a private instance method in a module works just like in a class, you use the private keyword. You can define private class methods using the private_class_method method.


1 Answers

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?

like image 160
kiddorails Avatar answered Sep 19 '22 07:09

kiddorails