From: Roger Pack Date: 2008-07-06T14:04:13+09:00 Subject: Re: Faking named parameters and enforcing required params Greg Willits wrote: > I come from years of using a language with named params. I prefer the > explicitness of it, so I'm tending to do a lot of it in my Ruby code > using a hash to fake it > > object.method(:shape=>'square', :size='medium') > > What I am wondering is whether there's an idiomatc preference to dealing > with the hash inside the method? > object->task(-shape='square', -size='large') # legal > object->task(-shape='square') # legal > object->task(-size='medium') # failed for lack of required param > > The required and optional features combined with some other stuff got > very close to a full design by contract implementation. Interestingly, I have also been working on something very similar to this recently. [a named parameter parser for ruby] Basically it parses an array as a parameter list, with some required and some optional parameters. ex: [first remember that you can pass parameters to a method via * for a variable number of parameters, i.e. def method *args; end passes in args as an array of all parameters] the syntax it uses is: def method1 *as required1, required2, optional1 = as.args [:required1, :required2], {:optional1 => 3} end and you call it either named or unnamedly, a la: method1 4, 5, 6 or method1 4, 5 or method1 :required1 => 1, :required2 => 2 or method1 :required1 => 1, :required2 => 2, :optional1 => 4 or method1 1, 2, :optional1 => 4 whichever floats your boat. Try it out, let me know if it works. the file is http://code.google.com/p/ruby-roger-useful-functions/source/browse/trunk/arg_parser/enhanced_arg_parser.rb and docs for it http://wilkboardonline.com/roger/arg_parser/doc/ [see args method for description]. Thanks! -R -- Posted via http://www.ruby-forum.com/.