Skip to content

Instantly share code, notes, and snippets.

@nevans
Last active February 16, 2023 23:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nevans/9374041 to your computer and use it in GitHub Desktop.
Save nevans/9374041 to your computer and use it in GitHub Desktop.
simple ruby console histogram generator
# Pass in an enumeration of data and
# (optionally) a block to extract the grouping aspect of the data.
#
# Optional: sort_by lambda (operates on group key and count)
#
def puts_hist(data, sort_by:nil, &blk)
data = data.map(&blk) if blk
counts = data.each_with_object(Hash.new(0)) {|k,h| h[k]+=1}
max = counts.values.max
width = Pry::Terminal.size!.last
width0 = counts.keys.map{|k|k.to_s.length}.max
width1 = width - width0 - 3
div = [1, max / width1.to_f].max
puts "max: %d; widths: %d, %d; divisor: %0.3f" % [max, width0, width1, div]
counts = counts.sort_by(&sort_by) if sort_by
counts.each do |k,c|
puts "%#{width0}s: %-#{width1}s" % [k, "#"*((c/div).round)]
end
counts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment