Esaki Raja
Esaki Raja

Reputation: 109

How to sort hashes in an array by keys?

Eg:

arr = ["c", "e", "a", {"hello" => [1,2,3]}, {"bell" => [4,5,6]}]

Above variable refers to an array which contains hashes along with strings. I need to write a function to sort this array alphabetically while the hashes being sorted by keys. Ideally it has to return the following:

["a", {"bell" => [4,5,6]}, "c", "e", {"hello" => [1,2,3]}]

Upvotes: 2

Views: 114

Answers (1)

Matthias Winkelmann
Matthias Winkelmann

Reputation: 16394

array.sort_by {|a| a.is_a?(Hash) ? a.keys.first : a }

Upvotes: 5

Related Questions