通过散列键或字符串按字母顺序排序数组的语法是什么?我想对以下内容进行排序:
['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']
给出以下内容:
['apple', 'bob', {'lasagne' => 'munch'}, 'sandwich', 'tangoed']
答案 0 :(得分:2)
当哈希包含多个键时,不清楚该怎么做。始终考虑哈希中的第一个键:
['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']
.sort_by{|e| [*e].flatten.first}
#=> ["apple", "bob", {"lasagne"=>"munch"}, "sandwich", "tangoed"]
答案 1 :(得分:0)
您可以将单词翻译成符号:
arr = ['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']
arr.sort_by { |e| e.is_a?(String) ? e : e.keys.first }
#=> ["apple", "bob", {"lasagne"=>"munch"}, "sandwich", "tangoed"]