Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashes vs. Multiple Params?

It is very common in Ruby to see methods that receive a hash of parameters instead of just passing the parameters to the method.

My question is - when do you use parameters for your method and when do you use a parameters hash?

Is it right to say that it is a good practice to use a parameter hash when the method has more than one or two parameters?

like image 834
Shay Friedman Avatar asked Aug 28 '09 16:08

Shay Friedman


People also ask

Is params a hash?

params is a method on the ActionController::StrongParameter class. While params appears to be a hash, it is actually an instance of the ActionController::Parameters class.


3 Answers

I use parameter hashes whenever they represent a set of options that semantically belong together. Any other parameters which are direct (often required) arguments to the function, I pass one by one.

like image 107
Matthias Avatar answered Sep 22 '22 16:09

Matthias


You may want to use a hash when there are many optional params, or when you want to accept arbitrary params, as you can see in many rails's methods.

like image 25
giorgian Avatar answered Sep 22 '22 16:09

giorgian


if you have more than 2 arguements. you should start thinking of using hash. This is good practise clearly explained in clean code link text

like image 36
Subba Rao Avatar answered Sep 22 '22 16:09

Subba Rao