From: Joel VanderWerf Date: 2006-03-27T04:29:28+09:00 Subject: Re: Verifying keyword arguments Eli Bendersky wrote: > Joel VanderWerf wrote: >> Ross Bamford wrote: >> .. >>> Not sure about libraries (though I'm sure they are out there, check RAA >>> and Rubyforge) but here's a little trick I've used before: >>> >>> args = { :one => 'two', :three => 'four' } >>> # => {:three=>"four", :one=>"two"} >>> >>> h = Hash.new { |h,k| raise ArgumentError, "#{k}" }.merge(args) >>> # => {:three=>"four", :one=>"two"} >>> >>> h[:one] >>> # => "two" >>> >>> h[:three] >>> # => "four" >>> >>> h[:two] >>> ArgumentError: two >>> from (irb):5 >>> from (irb):11 >>> >>> This way, you never actually check the arguments explicitly, but you'll >>> be told if your method uses one that wasn't passed. Obviously for >>> optional arguments you go to the original hash. >>> >> What about using rescue for optional arguments? It might be slower though. >> > > What do you mean ? Can you provide an example ? > args = { :one => 'two', :three => 'four' } # => {:three=>"four", :one=>"two"} h = Hash.new { |h,k| raise ArgumentError, "#{k}" }.merge(args) # => {:three=>"four", :one=>"two"} h[:one] # => "two" h[:three] # => "four" v = h[:two] rescue "this string is the default for 'two'" p v # => "this string is the default for 'two'" -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407