ruby: how to find non-unique elements in array and print each with number of occurrences?

puts a.uniq.
       map { | e | [a.count(e), e] }.
       select { | c, _ | c > 1 }.
       sort.reverse.
       map { | c, e | "#{e}:#{c}" }

The group_by method is used for this often:

a.group_by{ |i| i }
{
    "a" => [
        [0] "a"
    ],
    "d" => [
        [0] "d"
    ],
    "c" => [
        [0] "c",
        [1] "c",
        [2] "c"
    ],
    "b" => [
        [0] "b",
        [1] "b"
    ]
}

I like:

a.group_by{ |i| i }.each_with_object({}) { |(k,v), h| h[k] = v.size }
{
    "a" => 1,
    "d" => 1,
    "c" => 3,
    "b" => 2
}

Or:

Hash[a.group_by{ |i| i }.map{ |k,v| [k, v.size] }]
{
    "a" => 1,
    "d" => 1,
    "c" => 3,
    "b" => 2
}

One of those might scratch your itch. From there you can reduce the result using a little test:

Hash[a.group_by{ |i| i }.map{ |k,v| v.size > 1 && [k, v.size] }]
{
    "c" => 3,
    "b" => 2
}

If you just want to print the information use:

puts a.group_by{ |i| i }.map{ |k,v| "#{k}: #{v.size}" }
a: 1
d: 1
c: 3
b: 2

Tags:

Arrays

Ruby