简体   繁体   中英

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]}]
array.sort_by {|a| a.is_a?(Hash) ? a.keys.first : a }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM