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.