Pass Optional Arguments to Ruby Method
This the Ruby way of passing optional arguments with default values into a method:
1 def awesomeness options = {} 2 #sensible defaults 3 opts = { 4 :name => "Jerod", 5 :handle => "sant0sk1", 6 :blog => "Standard Deviations" 7 }.merge options 8 9 opts.each { |key,value| puts "#{key} = #{value}" } 10 end
When called sans arguments this function will print the following:
1 awesomeness 2 handle = sant0sk1 3 name = Jerod 4 blog = Standard Deviations
When called with arguments this function will merge them into the opts variable and print the following:
1 awesomeness :name => "Dork" 2 handle = sant0sk1 3 name = Dork 4 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.
0 comments
