【问题标题】:Group array of hashes by value and retain structure (hash) in Ruby按值分组哈希数组并在Ruby中保留结构(哈希)
【发布时间】:2020-10-09 03:20:16
【问题描述】:

我有一个这样的哈希:

  hash = {
    'en-us': {
      where: 'USA'
    },
    'en-us-zone2': {
      where: 'USA'
    },
    'en-nl': {
      where: 'Netherlands'
    },
    'en-pt': {
      where: 'Portugal'
    },
  }

我尝试使用group_by 对它们进行分组:

result = hash.group_by { |k,v| v[:where] }

但是,它返回完整的数组而不是哈希数组。所以这里是预期和实际的结果:

实际结果:

{ "USA"=>  
  [[:"en-us", {:where=>"USA"}], [:"en-us-zone2", {:where=>"USA"}]], 
 "Netherlands"=>
  [[:"en-nl", {:where=>"Netherlands"}]],
 "Portugal"=>
  [[:"en-pt", {:where=>"Portugal"}]]
}

预期结果:

{ "USA"=>
   [{:"en-us" => {:where=>"USA"}}, {:"en-us-zone2" => {:where=>"USA"}}]
  "Netherlands"=>
   [{:"en-nl" => {:where=>"Netherlands"}}]
  "Portugal"=>
   [{:"en-pt" => {:where=>"Portugal"}}]
}

请看,Actual 是数组数组,而不是哈希数组。哈希键成为第一个数组元素。

如何根据:where 对我的哈希进行分组?

【问题讨论】:

    标签: ruby hash


    【解决方案1】:

    它很丑但很有效:

    hash = {
      'en-us': {
        where: 'USA'
      },
      'en-us-zone2': {
        where: 'USA'
      },
      'en-nl': {
        where: 'Netherlands'
      },
      'en-pt': {
        where: 'Portugal'
      },
    }
    
    hash.
      group_by { |_, v| v[:where] }.
      map do |k, v|
        [
          k,
          v.map { |a, b| {a => b} }
        ]
      end.to_h
    
    # => {"USA"=>[{:"en-us"=>{:where=>"USA"}}, {:"en-us-zone2"=>{:where=>"USA"}}], "Netherlands"=>[{:"en-nl"=>{:where=>"Netherlands"}}], "Portugal"=>[{:"en-pt"=>{:where=>"Portugal"}}]}
    

    【讨论】:

      【解决方案2】:

      这应该可行:

      hash.group_by { |k,v| v[:where] }.each { |_, v| v.map! { |array| { array[0] => array[1] } } }
      

      或者使用 transform_values

      hash.group_by { |k,v| v[:where] }.transform_values { |v| v.map { |array| {array[0] => array[1] } } }
      

      https://ruby-doc.org/core-2.4.0/Hash.html#method-i-transform_values

      【讨论】:

      • 太棒了!它适用于我的“复杂”哈希。 (问题被简化)。谢谢!
      • 不用担心,很高兴我能帮上忙!请不要忘记接受答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2021-02-05
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      相关资源
      最近更新 更多