Pass Optional Arguments to Ruby Method
Posted: July 24th, 2008 | Author: Jerod | Filed under: Ruby | CommentsThis 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.