Options hash is a nice concept enabled by a feature of ruby parser. Say, you have a method with some required arguments. Also you may pass some optional arguments. Over time you may add more optional arguments or remove old ones. To keep method declaration clean and stable, you can pass all those optional arguments in a hash. Such method would look like this:
def foo(arg1, arg2, opts = {})
opts.to_s # just return a string value of opts
end
So it has two required values and last argument with default value of hash. If you don’t have any optional arguments to pass, you call it like this:
foo(1, 2) # => "{}"
If you do have something optional, you call it like this:
foo(1, 2, {truncate: true, redirect_to: "https://stackoverflow.com/"}) # => "{:truncate=>true, :redirect_to=>\"/\"}"
This code is so idiomatic to ruby that its parser actually allows you to omit curly braces when passing hash as a last argument to a method:
foo(1, 2, truncate: true, redirect_to: "https://stackoverflow.com/") # => "{:truncate=>true, :redirect_to=>\"/\"}"
If you use rails, for example, you’ll see options hashes everywhere. Here, I opened just a random controller in my app:
class ProductsController < ApplicationController
before_filter :prepare_search_params, only: :index
# ^^^^^^^^^^ options hash here
So, in short: options hash is argument of a method which is located last and has default value of {}
. And you normally pass hashes to it (hence the name).