From: Greg Willits Date: 2008-06-24T15:12:25+09:00 Subject: Faking named parameters and enforcing required params 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? Currently, I just do the prozaic: def task(parameters) shape = parameters[:shape] size = parameters[:size] Should I be doing something else? In that other language (Lasso), it also offered a way to declare required and optional parameters define_tag:'task', -required = 'shape', -optional = 'size'; ...blah... /define_tag; which then got used like this: 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. Anyway, I figured out I could simulate the assignment side of required and optional with this: def task(parameters) @shape = parameters[:shape] @size = parameters[:size] ||= 'medium' What I have't figured out is an elegant pattern in Ruby for enforcing required parameters -- other than a bunch of hand written exception coding. To summarize my questions: A) is there something better than x = parameters[:x]? B) if :x isn't in (parameters), what's the best way to complain to the developer about that? Many thanks. -- gw -- Posted via http://www.ruby-forum.com/.