Pass Optional Arguments to Ruby Method

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.



©Jerod Santo. Compiled from source by Jekyll. Original design credited to Jeff Kreeftmeijer.