您的位置:首页 > 其它

Sorting a mixed array of hashes and strings

2014-09-06 16:10 232 查看
What is the syntax for sorting an array alphabetically by the key of a hash or by a string? I would like to sort the following:
['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']


to give the following:
['apple', 'bob', {'lasagne' => 'munch'}, 'sandwich', 'tangoed']


Not clear what to do when a hash includes more than one key. Considering always the first key in a hash:
['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']
.sort_by{|e| [*e].flatten.first}
#=> ["apple", "bob", {"lasagne"=>"munch"}, "sandwich", "tangoed"]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: