This guide examines how to build a histogram in Ruby that takes in an Array of integers and returns a Hash that counts the number of occurrences of each integer.
Summary
Build a histogram in Ruby that returns a hash.
Exercise File
Exercise Description
Given the following array of integers:
[1, 4, 1, 3, 2, 1, 4, 5, 4, 4, 5, 4]
Build out a method that generates a histogram in hash form where the key is the integer that is being counted, and the value is the number of occurrences.
Expected Output
{ 1=>3, 4=>5, 3=>1, 2=>1, 5=>2 }
Real World Usage
Counting the number of occurrences of a value in a collection is a common practice. Imagine that you need to calculate the number of times that a user has commented on a friend’s picture in a social media application.
Solution
Can be found on the solutions branch on github.
Rubocop prefers each_with_object over inject method.
But that doesn’t work like it is.
I get this error
Failure/Error: hash[element] += 1
TypeError:
no implicit conversion of Hash into Integer
# ./13.rb:7:in `[]’
# ./13.rb:7:in `block in num_counter’
# ./13.rb:6:in `each’
# ./13.rb:6:in `each_with_object’
# ./13.rb:6:in `num_counter’
# ./13.rb:16:in `block (2 levels) in ‘
We have to reverse the arguments for each_with_object.
Here’s an example https://jerodsanto.net/2013/10/ruby-quick-tip-easily-count-occurrences-of-array-elements/