6

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?

ire_and_curses
  • 68,372
  • 23
  • 116
  • 141
Shay Friedman
  • 4,808
  • 5
  • 35
  • 51

5 Answers5

4

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.

mxk
  • 43,056
  • 28
  • 105
  • 132
  • 1
    +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 Aug 28 '09 at 16:56
1

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
  • 3,795
  • 1
  • 30
  • 48
1

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
  • 10,576
  • 7
  • 29
  • 31
0

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.

aehlke
  • 15,225
  • 5
  • 36
  • 45
0

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.

mxk
  • 43,056
  • 28
  • 105
  • 132