Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest/One-liner way to collect duplicates in Ruby Array?

Tags:

arrays

ruby

What's the fastest/one-liner way to convert an array like this:

[1, 1, 1, 1, 2, 2, 3, 5, 5, 5, 8, 13, 21, 21, 21]

...into an array of objects like this:

[{1 => 4}, {2 => 2}, {3 => 1}, {5 => 3}, {8 => 1}, {13 => 1}, {21 => 3}]

like image 844
Lance Avatar asked Oct 01 '09 08:10

Lance


2 Answers

To achieve your desired format, you could append a call to map to your solution:

array.inject({}) { |h,v| h[v] ||= 0; h[v] += 1; h }.map {|k, v| {k => v}}

Although it still is a one-liner, it starts to get messy.

like image 174
jgre Avatar answered Sep 25 '22 21:09

jgre


super basic, finally understand inject:

array.inject({}) { |h,v| h[v] ||= 0; h[v] += 1; h }

Not totally there, but almost

like image 25
Lance Avatar answered Sep 23 '22 21:09

Lance