When a Ruby method call's argument list ends in one or more key-value pairs, like foo: 'bar'
or 'foo' => 1
, Ruby collects them all into a single hash and passes that hash as the last parameter. You can see that yourself in irb
:
irb(main):002:0> puts foo: 'bar', baz: 'quux'
{:foo=>"bar", :baz=>"quux"}
=> nil
Thus, you can add a final, optional parameter to a method you're writing to receive this hash. You'll usually want to default it to an empty hash. You can call the parameter anything you want, but options
is a common name:
def my_method(a, b, c, options = {})
...
end
One useful trick if you're using Rails: It's often handy to treat plain strings and symbols as equivalent. Rails adds a symbolize_keys!
method to Hash
to convert all string keys to symbols:
def my_method(a, b, c, options = {})
options.symbolize_keys!
...
end