Counting Elements with Ruby Hashes

Understanding the Problem

We begin in a library, where we want to count book copies. With a small collection, we might be able to tally each one manually. However, as the collection grows, this approach becomes cumbersome and inefficient. A more efficient method uses Hashes in Ruby.

For a quick illustration, consider this array of colors:

colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']

If we count manually, red appears twice, blue appears thrice, and green appears once. We can employ Hashes for a more efficient counting process.

Introducing Hashes

Simple yet powerful, Hashes allow us to store and retrieve data using keys. The unique colors in our array act as keys, and the count of each color becomes its corresponding value. Let's demonstrate how we can count elements in our colors array using a Ruby hash:

colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
color_hash = {}

# Start the loop to iterate over each color
colors.each do |color|
  # If the color is present in our hash, increment its value by 1
  if color_hash.has_key?(color)
    color_hash[color] += 1
  # If the color isn't present, it means we're encountering this color in our array for the first time. In this case, we add it to our hash and set its value to 1
  else
    color_hash[color] = 1
  end
end

# At the end of the loop, print our hash with counts
puts color_hash
# prints {"red"=>2, "blue"=>3, "green"=>1}

When the above code executes, it displays the counts for each color: {"red"=>2, "blue"=>3, "green"=>1}.

Understanding the Above Solution

Here's how we created a hash to count our elements:

We began with an empty hash. Then, we went through our array, and for every occurring element, we checked if it was in our hash. If it was, we increased its value. If it was not, we added it to the hash with a value of 1.

Consequently, this code efficiently counts the colors in our array, showcasing how performant counting can be, even as the array size increases!

In Ruby, hashes allow us to set a default value for keys that do not exist. This can be used to simplify our code. We can write the above example like this:

colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
color_hash = Hash.new(0)

# Start the loop to iterate over each color
colors.each do |color|
  # Increment the value for the color key
  color_hash[color] += 1
end

# At the end of the loop, print our hash with counts
puts color_hash
# prints {"red"=>2, "blue"=>3, "green"=>1}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal