Leonhard Euler
Leonhard Euler

Reputation: 11

In Ruby how do I sort a hash by its key values in alphabetical order?

Suppose I have a hash, {"c": 1, "b": 2, "a": 3} How do I sort the hash so the elements are in order of the key value?

Upvotes: 0

Views: 424

Answers (2)

Jikku Jose
Jikku Jose

Reputation: 18804

{"c" => 1, "b" => 2, "a" => 3}.sort.to_h

Upvotes: 1

Planet of the Abes
Planet of the Abes

Reputation: 5

myh = {"c" => 1, "b" => 2, "a" => 3}

myh.sort

=> [["a", 3], ["b", 2], ["c", 1]]

Upvotes: 1

Related Questions