Passing options in Ruby

A neat idiom for passing options to a class in Ruby …

class WithOptions
  def initialize(opts = {})
    @options = {
      :debug => false
    }.merge(opts)
  end
end
foo = WithOptions.new(:debug => true)

# or ...

other_opts = {
  :debug => true,
  :debug_level => :WARN
}
foo = WithOptions.new(other_opts)

Any options passed will be merged with the default options setup in the class. Options with the same name will override the default options. The same technique can be used with methods.

An alternative approach is to specify the defaults directly in the default options hash parameter.

def some_method(opts = {:debug => false})
  puts opts[:debug]
end

Tags:

2 Responses to “Passing options in Ruby”

  1. matnotfat says:

    As frequently seen in the jQuery plugins. It really does work nice. It lets you offer tons of options, and keep it transparent to the user for most cases.

  2. Seanba says:

    Nice. The merge API on hashtables is a great feature.