【问题标题】:Sorting a mixed array of hashes and strings对哈希和字符串的混合数组进行排序
【发布时间】:2014-08-11 10:15:30
【问题描述】:

按照哈希键或字符串的字母顺序对数组进行排序的语法是什么?我想对以下内容进行排序:

['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']

给出以下内容:

['apple', 'bob', {'lasagne' => 'munch'}, 'sandwich', 'tangoed']

【问题讨论】:

    标签: ruby arrays sorting hash


    【解决方案1】:

    不清楚当哈希包含多个键时该怎么做。始终考虑哈希中的第一个键:

    ['bob', 'apple', 'sandwich', {'lasagne' => 'munch'}, 'tangoed']
    .sort_by{|e| [*e].flatten.first}
    #=> ["apple", "bob", {"lasagne"=>"munch"}, "sandwich", "tangoed"]
    

    【讨论】:

    • 嗨 Sawa 感谢您的回答,您能告诉我 [*e] 部分在展平之前的作用吗?
    • 如果定义了to_a(哈希就是这种情况),那么它将to_a应用于它,删除它周围的[],并用另一个[]包围它。否则(字符串就是这种情况),它用[]包围它。
    【解决方案2】:

    你可以把你的话翻译成符号:

    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"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      相关资源
      最近更新 更多