You can make the last argument an optional hash to achieve this:
def some_method(x, options = {})
However, in Ruby 2.0.0 it is usually best to use the new keyword argument function:
def some_method(x, other_arg: "value1", other_arg2: "value2")
Benefits of using the new syntax instead of using a hash:
- This introduces access to optional arguments less (for example,
other_arg instead of options[:other_arg] ). - It is easy to specify a default value for optional arguments.
- Ruby will automatically detect that the caller used an invalid argument name and threw an exception.
One of the drawbacks of the new syntax is that you cannot (as far as I know) easily send all keyword arguments to another method because you do not have a hash object that represents them.
Fortunately, the syntax for calling these two types of methods is the same, so you can move from one to the other without breaking good code.
source share