From: Josh Cheek Date: 2011-06-22T00:11:28+09:00 Subject: Re: How to order a hash based on its keys? --90e6ba4fc300ec8ee504a63a4344 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable (Resending this b/c it looks like it got blocked or the server crashed the first time. Hopefully it's not a duplicate) On Tue, Jun 21, 2011 at 9:34 AM, I=F1aki Baz Castillo wrote= : > Hi, I want to order a hash using itds keys: > > irb> a =3D { 2=3D>"2", 3=3D>"3", 1=3D>"1" } > irb> a.sort > [[1, "1"], [2, "2"], [3, "3"]] > > But I want a resulting hash with keys ordered: > > { 1=3D>"1", 2=3D>"2", 3=3D>"3"} > > Is there any efficiente way? (I don't want the hast to be converted to > an array and the to a hash again). > > Thanks. > > -- > I=F1aki Baz Castillo > > > You could create your own data structure which keeps the elements sorted an= d supports the hash interface, ie https://gist.github.com/1038031 I don't know if the overhead of keeping them sorted (in this case, in a BST= ) is lower than the overhead of the Array. But if you are frequently iteratin= g over it, I would expect it to pay off (ie you would have to create a new array each time you iterate over a Hash, but you will not have to create over a SortedHash. So probably depends on the use case. --90e6ba4fc300ec8ee504a63a4344--