从下面的哈希值中,需要提取每个键的唯一值
array_of_hashes = [ {'a' => 1, 'b' => 2 , 'c' => 3} ,
{'a' => 4, 'b' => 5 , 'c' => 3},
{'a' => 6, 'b' => 5 , 'c' => 3} ]
Run Code Online (Sandbox Code Playgroud)
需要提取数组中每个键的唯一值
"a"的唯一值应该给出
[1,4,6]
Run Code Online (Sandbox Code Playgroud)
'b'的唯一值应该给出
[2,5]
Run Code Online (Sandbox Code Playgroud)
'c'的唯一值应该给出
[3]
Run Code Online (Sandbox Code Playgroud)
想法?
fal*_*tru 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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10119 次 |
| 最近记录: |