From: "Ara.T.Howard" Date: 2005-07-19T23:13:52+09:00 Subject: Re: [RCR] nil for unassigned keys On Tue, 19 Jul 2005, Simon Strandgaard wrote: > On 7/19/05, Yukihiro Matsumoto wrote: >> on Tue, 19 Jul 2005 20:40:47 +0900, Simon Strandgaard writes: >> >> |Sometimes I find myself writing :key=>true, >> |it would be nice if one didn't had to do assignment, >> |so its value instead defaulted to nil. >> | >> |def test(hash={}) >> | p hash >> |end >> | >> |test('x', 'y'=>2, 'z') # {"x"=>nil, "y"=>2, "z"=>nil} >> >> In that case, how can we distinguish a hash key without value and >> ordinal mandatory argument? > > Maybe I don't understand the mandatory argument thing? > But can't you just count them somehow? not when there are zero or more allowed, for instance def test(*args, &block) x = args.shift || 42 hash = Hash === x ? x : (args.shift || {}) y, z = hash.values_at 'x', 'z' p [x,y,z] end which allows test() test('y' => 42) test('y' => 42, 'z' => 42.0) test('x as forty-two') test('x as forty-two', 'y' => 42) test('x as forty-two', 'y' => 42, 'z' => 42.0) maybe it's possible - but it seems like kleeny star makes it pretty tough. why not a little helper function to transform argument lists in the way you desire? def h(*list) list.inject({}) do |hash,elem| hash.update(Hash === elem ? {elem => nil} : elem) end end which at least allows test(h('x', 'z', 'y' => 42)) though not test(h('x', 'y' => 42, 'z')) cheers. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | My religion is very simple. My religion is kindness. | --Tenzin Gyatso ===============================================================================