--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ñáki Baz Castillo <ibc / aliax.net> wrote: > Hi, I want to order a hash using itds keys: > > irb> a = { 2=>"2", 3=>"3", 1=>"1" } > irb> a.sort > [[1, "1"], [2, "2"], [3, "3"]] > > But I want a resulting hash with keys ordered: > > { 1=>"1", 2=>"2", 3=>"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ñáki Baz Castillo > <ibc / aliax.net> > > You could create your own data structure which keeps the elements sorted and 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 iterating 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--