views:

129

answers:

5

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?

A: 

One obvious use case is when you are overriding a method in a child class, you should use hash parameters for the parent method's parameters for when you call it.

Wahnfrieden
+4  A: 

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.

Matthias
+1 - nothing in a parameter hash should be required. Optional parameters could be named, with default values, but I tend to pass them in a hash and set defaults in the method body if needed.
Sarah Mei
+1  A: 

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.

giorgian
A: 

On another note, and this is not only related to Ruby but to all languages:

In APIs which are in flux, it is sometimes useful to declare some or all parameters to a function as a single parameters object (in Ruby these could be hashes, in C structs, and so on), so as to maintain API stability should the set of accepted arguments change in future versions. However, the obvious downside is that readability is drastically reduced, and I would never use this "pattern" unless I'd really really have to.

Matthias
+1  A: 

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

Subba Rao