I\'m playing with Ruby on Rails and I\'m trying to create a method with optional parameters. Apparently there are many ways to do it. I trying naming the optional parameters
The problem is the default value of options
is the entire Hash
in the second version you posted. So, the default value, the entire Hash
, gets overridden. That's why passing nothing works, because this activates the default value which is the Hash
and entering all of them also works, because it is overwriting the default value with a Hash
of identical keys.
I highly suggest using an Array
to capture all additional objects that are at the end of your method call.
def my_info(name, *args)
options = args.extract_options!
age = options[:age] || 27
end
I learned this trick from reading through the source for Rails. However, note that this only works if you include ActiveSupport. Or, if you don't want the overhead of the entire ActiveSupport gem, just use the two methods added to Hash
and Array
that make this possible.
rails / activesupport / lib / active_support / core_ext / array / extract_options.rb
So when you call your method, call it much like you would any other Rails helper method with additional options.
my_info "Ned Stark", "Winter is coming", :city => "Winterfell"