Reputation: 4868
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?
Upvotes: 6
Views: 609
Reputation: 10676
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
Upvotes: 1
Reputation: 43524
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.
Upvotes: 0
Reputation: 3825
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.
Upvotes: 1
Reputation: 43524
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.
Upvotes: 4
Reputation: 15831
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.
Upvotes: 0