Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - extracting the unique values per key from an array of hashes

Tags:

arrays

ruby

hash

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 ?

like image 855
user3206440 Avatar asked Jan 17 '14 12:01

user3206440


People also ask

How do I get the hash value in Ruby?

In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.

What is Array of hashes in Ruby?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

Do hashes have indexes Ruby?

A Hash is a collection of key-value pairs. It is similar to an Array , except that indexing is done via arbitrary keys of any object type, not an integer index.


1 Answers

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]
like image 173
falsetru Avatar answered Oct 24 '22 17:10

falsetru