Passing hashes instead of method parameters [closed] Passing hashes instead of method parameters [closed] ruby ruby

Passing hashes instead of method parameters [closed]


Ruby has implicit hash parameters, so you could also write

def my_method(options = {}) my_method(:width => 400, :height => 50, :show_border => false)

and with Ruby 1.9 and new hash syntax it can be

my_method( width: 400, height: 50, show_border: false )

When a function takes more than 3-4 parameters, it's much easier to see which is what, without counting the respective positions.


Both approaches have their own advantages and disadvantages, when you use an options hash replacing standard arguments you lose clarity in the code defining the method but gain clarity whenever you use the method because of the pseudo-named paramaters created by using an options hash.

My general rule is if you either have a lot of arguments for a method (more than 3 or 4) or lots of optional arguments then use an options hash otherwise use standard arguments. However when using an options hash it is important to always include a comment with the method definition describing the possible arguments.


I'd say that if you are either:

  1. Having more than 6 method parameters
  2. Passing options that have some required, some optional and some with default values

You would most probably want to use a hash. It's much easier to see what the arguments mean without looking up in the documentation.

To those of you saying it's hard to figure what options a method takes, that just means that the code is poorly documented. With YARD, you can use the @option tag to specify options:

### Create a box.## @param [Hash] options The options hash.# @option options [Numeric] :width The width of the box.# @option options [Numeric] :height The height of the box.# @option options [Boolean] :show_border (false) Whether to show a#   border or not.def create_box(options={})  options[:show_border] ||= falseend

But in that specific example there's such few and simple parameters, so I think I'd go with this:

### Create a box.## @param [Numeric] width The width of the box.# @param [Numeric] height The height of the box.# @param [Boolean] show_border Whether to show a border or not.def create_box(width, height, show_border=false)end