Histograms in Ruby

A histogram is a type of distribution that shows the frequency of each value. Plotting histograms allows you to visualise the data. Here is an example histogram plot:

 Histogram representation in Ruby

Here is a simple histogram implementation in Ruby:

class Histogram
  def initialize(list)
    @histogram = {}
    build_histogram(list)
  end

  def frequency(n)
    @histogram[n] || 0
  end

  private

  def build_histogram(list)
    list.each do |v|
      @histogram[v] = list.count(v)
    end
  end
end

This Histogram class allows you to pass in a list of values and get the frequencies of each of the values.

hist = Histogram.new([1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 5])
hist.frequency(2) # => 5
hist.frequency(4) # => 0

Plotting a histogram in Ruby

Stay tuned, I will be updating this page soon explaining how you can plot this histogram representation in Ruby.