Question

I'm still a ruby / rails beginner and am a little stuck here.

Here's what I have: I have an array of hashes, each hash contains multiple keys, f.e.: firstname, lastname, nickname, birthday

Before further processing, I want to get all duplicate hashes. I know this can be done with merge. There is one tricky thing: I have a special criteria for "duplicates". I want to check each hash and only count is as duplicate if the three keys firstname, lastname and nickname are identical. If that's the case, I want to remove all duplicates from the array and append a new key "count" to the last entry which holds the number of occurences.

I have the feeling that enumerations will lead me to success, but I have no idea how to approach this problem in an elegant "rails" way.

Your help is much appreciated!

Kind regards, madhippie.

Was it helpful?

Solution

uniq takes a block in later versions of ruby but as you also need the count I would start looking into the group_by method:

result = hash.group_by{|x| x.values_at(:firstname, :lastname, :nickname)}

Then it is just a matter of grabbing a hash and adding the number of values:

result.map{|_,values| values.first.merge {size: values.lenth}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top