本文介绍了Ruby - 从哈希数组中提取每个键的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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] 

想法? 使用:

  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]


From a hash like the below one, need to extract the unique values per key

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

Need to extract the unique values per key in an array

unique values for 'a' should give

[1,4,6]

unique values for 'b' should give

[2,5]

unique values for 'c' should give

[3]

Thoughts ?

解决方案

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

这篇关于Ruby - 从哈希数组中提取每个键的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 02:38