-1

I usually sort ruby hashes using the very famous sort method as given in my example below. But this terribly fails when the string key has an underscore in it. For eg:

h = {"b" => 1, "a" => 2}
Hash[h.sort]

sorts the hash perfectly. But when the hash is something like

h = {"b_d" => 1, "a_v" => 2}

I do not get the desired sort order. The point to note here is h.sort sorts the hash and produces an Enumerable object. But when I convert the object back to Hash using Hash[h.sort], it loses the order here. Any suggestions for a better process could be helpful.

Note: I'm using Ruby 1.8.7, so an OrderedHash is not much in my lenses.

Aravind
  • 221
  • 4
  • 13
  • What's the difference? Why are you sorting it? – shime Oct 02 '12 at 12:58
  • To sign an OAuth request where the params string should be ordered. – Aravind Oct 02 '12 at 13:00
  • 1
    Your assertion that the first example "sorts the hash perfectly" is likely to be coincidence. If you only have 2 keys it's a 50% chance that any pseudo-random ordering will be "correct" – Gareth Oct 02 '12 at 13:01

1 Answers1

2

In Ruby 1.8.7, as soon as you convert back to a Hash you necessarily lose your ordering. You'll have to get rid of the vanilla Hash to get this to work - maybe try keeping the Enumerable you get back from sort and using that for as long as possible?

Gareth
  • 133,157
  • 36
  • 148
  • 157