Insights on Ruby, Git, jQuery, Cappuccino, WordPress, Debian and OS X. Please subscribe if you find something useful!

Pass Optional Arguments to Ruby Method

Posted: July 24th, 2008 | Author: Jerod | Filed under: Ruby | Comments Off

This is the Ruby way of passing optional arguments with default values into a method:

def awesomeness options = {}
  #sensible defaults
  opts = {
   :name => "Jerod",
   :handle => "sant0sk1",
   :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 = sant0sk1
name = Jerod
blog = Standard Deviations

When called with arguments this function will merge them into the opts variable and print the following:

awesomeness
handle = sant0sk1
name = Jerod
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.


Comments are closed.