From: Josh Cheek Date: 2010-06-18T00:25:36+09:00 Subject: Re: method interface - hash argument vs. named parameters --0016e6d7e345efa7e604893b7238 Content-Type: text/plain; charset=ISO-8859-1 On Thu, Jun 17, 2010 at 9:24 AM, Intransition wrote: > I've never run into this issue before, but I'm working on a method > interface that is quite 'dense', and I need to be able to > differentiate between a hash passed to a method and named parameters. > i.e. All of these are valid: > > foo(hash, :opt=>val) > foo(hash) > foo(:opt=>val) > > However, there seems to be no way to distinguish that last the two > forms. > > Is there any way? Or am I stuck? > > I would expect stuck, because the difference seems nothing more than visual. (ie if the options hash was assigned to a var, rather than created within the arg list, then the last two would be exactly the same) though it does seem unusual that there is not a method like options_given? the way there is a block_given? I suppose if this method interface is absolutely necessary, then a hack you might be able to get away with would be to check the keys to see if they match up with your options. But I would be embarrassed to show anyone such a solution ;) Something to consider, though, whatever param the hash is an arg for, is optional (ie omitted in your third invocation). So perhaps it would fit better into the options hash, which you could then extract it from, inside the method: def foo( options = Hash.new ) the_hash = options.delete(:the_hash) { Hash.new } [ the_hash , options ] end hash = Hash[*1..4] val = :val foo( :the_hash => hash , :opt => val ) # => [{1=>2, 3=>4}, {:opt=>:val}] foo( :the_hash => hash ) # => [{1=>2, 3=>4}, {}] foo( :opt => val ) # => [{}, {:opt=>:val}] --0016e6d7e345efa7e604893b7238--