I can't find a simple solution for this problem
For example we have an array:
["a", "a", "a", "a", "a", "b", "b", "c", "a", "a", "a"]
I need to count the identical elements in this way:
[["a", 5], ["b", 2], ["c", 1], ["a", 3]]
I can't find a simple solution for this problem
For example we have an array:
["a", "a", "a", "a", "a", "b", "b", "c", "a", "a", "a"]
I need to count the identical elements in this way:
[["a", 5], ["b", 2], ["c", 1], ["a", 3]]
Uses the chunk method to group identical elements, then uses map to convert [letter, array] pairs to [letter, count].
arr = ["a", "a", "a", "a", "a", "b", "b", "c", "a", "a", "a"]
counted = arr.chunk { |x| x }.map { |a, b| [a, b.count] }
# => [["a", 5], ["b", 2], ["c", 1], ["a", 3]]
counted = arr.sort.chunk { |x| x }.map { |a, b| [a, b.count] }In Ruby 2.2 you could use Enumable#slice_when:
arr = ["a", "a", "a", "a", "a", "b", "b", "c", "a", "a", "a"]
arr.slice_when { |e,f| e!=f }.map { |a| [a.first, a.size] }
#=> [["a", 5], ["b", 2], ["c", 1], ["a", 3]]