【问题标题】:Ruby - extracting the unique values per key from an array of hashesRuby - 从散列数组中提取每个键的唯一值
【发布时间】:2014-01-17 12:29:09
【问题描述】:

从像下面这样的哈希中,需要提取每个键的唯一值

array_of_hashes = [ {'a' => 1, 'b' => 2 , 'c' => 3} , 
                    {'a' => 4, 'b' => 5 , 'c' => 3}, 
                    {'a' => 6, 'b' => 5 , 'c' => 3} ]

需要提取数组中每个键的唯一值

'a' 的唯一值应该给出

[1,4,6]

'b' 的唯一值应该给出

[2,5]

'c' 的唯一值应该给出

[3]

想法?

【问题讨论】:

    标签: ruby arrays hash


    【解决方案1】:

    使用Array#uniq:

    array_of_hashes = [ {'a' => 1, 'b' => 2 , 'c' => 3} , 
                        {'a' => 4, 'b' => 5 , 'c' => 3}, 
                        {'a' => 6, 'b' => 5 , 'c' => 3} ]
    
    array_of_hashes.map { |h| h['a'] }.uniq    # => [1, 4, 6]
    array_of_hashes.map { |h| h['b'] }.uniq    # => [2, 5]
    array_of_hashes.map { |h| h['c'] }.uniq    # => [3]
    

    【讨论】:

    • |h| 是一个块参数。
    【解决方案2】:

    这是更通用的:

    options = {}
    distinct_keys = array_of_hashes.map(&:keys).flatten.uniq
    distinct_keys.each do |k|
      options[k] = array_of_hashes.map {|o| o[k]}.uniq
    end
    

    【讨论】:

      猜你喜欢
      • 2013-05-11
      • 2012-03-15
      • 2020-09-10
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2013-05-23
      相关资源
      最近更新 更多