【问题标题】:Ruby: Transform two-dimensional array into sorted hash with keys based on the first letter of the first elementRuby:将二维数组转换为带有基于第一个元素的第一个字母的键的排序哈希
【发布时间】:2013-01-29 01:19:34
【问题描述】:

假设我有以下二维数组(未排序)

[["Abigail", 1047], ["Betty", 1049], ["Alfred", 1048], ["Bernadette", 1050]]

如何根据第一个元素的第一个字母将其转换为带有字母键的哈希?需要根据第一个元素(即本例中的人名)对键和数组元素进行排序:

{
'A' => [['Abigail','1047'], ['Alfred','1048']],
'B' => [['Bernadette','1050'], ['Betty','1049']]
}

【问题讨论】:

    标签: ruby


    【解决方案1】:
    a = [["Abigail", 1047], ["Betty", 1049], ["Alfred", 1048], ["Bernadette", 1050]]
    p Hash[a.sort.chunk{|x| x[0][0]}.to_a]
    

    适用于 1.9.x

    【讨论】:

    • 我喜欢!我不知道Enumerable#chunk
    • 完美。很优雅,不知道chunk
    • 注意可以解压chunk中的数组对:chunk { |name, n| name[0] }.
    【解决方案2】:
    a = [["Abigail", 1047], ["Betty", 1049], ["Alfred", 1048], ["Bernadette", 1050]]
    p a.sort.group_by{|el| el.first[0]}
    

    sort 数组以确保散列中的键已排序(在 1.9 中),group_by 第一个元素的第一个字母(名称)。

    【讨论】:

      【解决方案3】:
      names_and_values = [["Abigail", 1047], ["Betty", 1049], ["Alfred", 1048], ["Bernadette", 1050]]
      #=> [["Abigail", 1047], ["Betty", 1049], ["Alfred", 1048], ["Bernadette", 1050]]
      names_and_values.sort.reduce({}) do |memo, name_and_value|
        name = name_and_value[0]
        initial = name[0]
        ( memo[initial] ||= [] ) << name_and_value
        memo
      end
      #=> {"A"=>[["Abigail", 1047], ["Alfred", 1048]], "B"=>[["Bernadette", 1050], ["Betty", 1049]]}
      

      【讨论】:

        猜你喜欢
        • 2012-10-01
        • 2014-08-27
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2021-08-25
        • 2013-12-04
        • 2021-07-28
        • 1970-01-01
        相关资源
        最近更新 更多