Pass Optional Arguments to Ruby Method
24 Jul 2008
This is the Ruby way of passing optional arguments with default values into a method:
def awesomeness options = {}
#sensible defaults
opts = {
:name => "Jerod",
:handle => "jerodsanto",
:blog => "Standard Deviations"
}.merge options
opts.each { |key,value| puts "#{key} = #{value}" }
end
When called sans arguments this function will print the following:
awesomeness
handle = jerodsanto
name = Jerod
blog = Standard Deviations
When called with arguments this function will merge them into the opts variable and print the following:
awesomeness :name => "Santo"
handle = jerodsanto
name = Santo
blog = Standard Deviations
The defaults are used unless you specify an override in the method call, in which case the override is merged into the opts hash.