I have an array: x = [a, b, c, d, e, f, g, h] which can have objects from 1 to 9
Firstly, I have to count IF any of these objects is present 3 times. I don’t want to write
if (x.count(1) == 3) or (x.count(2) == 3) ...etc...
is there a way to shorten this, like below?
x.count { |obj| obj } == 3
Secondly, if I know that an object has been found with 3 instances, how can I find out which one was it? (1 or 2 or 3…..)
How does this work? Let’s follow the steps. First, let’s group the items by count:
This produces a hash with the keys being the counts, and the values being the list of non-unique items having that count:
We’d really rather have unique items, though, so let’s do that transform:
That gives us an array of arrays, and not a hash. Fortunately, it’s easy to turn an array of arrays into a hash:
Now just put the pieces together eliminating the temporaries and you get the answer at the top.