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}]
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}]
super basic, finally understand inject:
array.inject({}) { |h,v| h[v] ||= 0; h[v] += 1; h }
Not totally there, but almost
To achieve your desired format, you could append a call to map to your solution:
Although it still is a one-liner, it starts to get messy.
Requires 1.8.7
Not a huge difference but I prefer to be explicit with what I am doing. Saying
Hash.new(0)
replaces{}
andh[v] ||= 0