Ruby - 从散列数组中提取每个键的唯一值

时间:2014-01-17 12:29:09

标签: ruby arrays hash

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

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]

想法?

2 个答案:

答案 0 :(得分:21)

使用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]

答案 1 :(得分:0)

这更通用:

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