From: Martin DeMello Date: 2004-08-17T18:00:58+09:00 Subject: Re: Q: Shifting a hash anf and array Robert Klemme wrote: > > > Hash[*(hash.keys.rot1.zip(hash.values.rot1).flatten)] > > Hm, IMHO there is one "rot1" too much: you're rotating keys *and* values > while you should only rotate one of them. Otherwise I figure the result > will be the same as the original hash... :-) Doh :) > The other drawback of your solution is that it relys on #keys and #values > returning elements in matching order, i.e., if you zip both you get the same > hash. Although that might work it makes me feel a bit wary because AFAIK > it's not a guaranteed property of Hash (and I wouldn't want to rely on it). > This might even change over time if the Hash implementation was changed for > any reasons. I know, but that was the only way I could think of to avoid the one-lookup-per-key. > How about these one liners, that avoids the problem: > > h = {0=>"a", 1=>"b", 2=>"c"} > # put rotated in h2 > (h2={}).send(:[]=, *h.sort.inject {|(k1,v1),(k2,v2)| h2[k1]=v2; [k2, v1]}) > # rotate inplace > h.send(:[]=, *h.sort.inject {|(k1,v1),(k2,v2)| h[k1]=v2; [k2, v1]}) Neat - I didn't know there was a Hash#sort martin