As a newcomer to the Ruby language, I’ve been leaning extra heavily on online Ruby documentation as I am not yet accustomed to many of Ruby’s common built-in methods. It wasn’t long though before I encountered a scenario that I thought would have a simple built-in method solution, but surprisingly didn’t.
I wanted to take an array of elements and turn it into a hash where the array elements would become keys, but duplicates of that element would be counted and stored as value of that key. For example:

As I soon discovered, there are many solutions to this problem. But before I show a few examples that you can implement yourself, should you be in a similar scenario, let me show you my first attempt and how I came to refactor my code into one of those more concise solutions.
My first attempt went something like this:

Not exactly elegant, but it does work as intended. My method takes in an array as an argument and iterates over that array to create a hash. As the .each method goes through my array elements one-by-one, it checks if that element is already a key in my new hash. If it isn’t, I create a new key and set the initial value to 1. If it is, I simply increment that key’s value by 1. At the end, I return my beautiful new hash.
Ok but this is clunky. The first thing that stands out is my conditional statement in the .each method. Is this really necessary? Not at all. A quick but significant change makes this simple to condense:

The big change here occurs in line 2. Hash.new(0) will give new hash keys a default value of 0, rather than the default nil value we had from the simpler { } assignment. This is what allows me to immediately increment a new key and eliminate my need for a conditional statement.
Since I can still make this code more concise without distorting the process, I’ll go ahead and do that. After all, it is always satisfying to have a clean 1 line solution.

Nice! A simple solution to a simple problem. However, when it comes to coding there is rarely only one way to go about solving a problem. Here I’ll share two additional solutions that I quite like:

Source: https://stackoverflow.com/questions/5128200/how-to-count-identical-string-elements-in-a-ruby-array

Source: http://carol-nichols.com/2015/08/07/ruby-occurrence-couting/