Fastest / single line duplicate collection method in Ruby Array?

What a quick / single line way to convert such an array:

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

... into an array of such objects:

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

+5
source share
4 answers

To achieve the desired format, you can add a call to match with your solution:

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

Although it is still single-line, it is starting to get confused.

+5
source

super basic finally understand the injection:

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

Not quite there, but almost

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

Not a big difference, but I prefer to be explicit with what I do. Expression Hash.new(0)replaces {}andh[v] ||= 0

+5
source

1.8.7 required

a = [1, 1, 1, 1, 2, 2, 3, 5, 5, 5, 8, 13, 21, 21, 21]
h = {}
a.group_by {|e| e}.each {|k,v| h[k] = v.length}
p h  # => {5=>3, 1=>4, 2=>2, 13=>1, 8=>1, 3=>1, 21=>3}
+4
source

All Articles