Passing hashes instead of method parameters

rmaruszewski picture rmaruszewski · Dec 18, 2009 · Viewed 43.1k times · Source

I see that in Ruby (and dynamically typed languages, in general) a very common practice is to pass a hash, instead of declaring concrete method parameters. For example, instead of declaring a method with parameters and calling it like this:

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

you can do it this way:

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

I'd like to know your opinion about it. Is it a good or a bad practice, should we do it or not? In what situation using this practice is valid, and it what situation can it be dangerous?

Answer

MBO picture MBO · Dec 18, 2009

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.