Skip to content

Instantly share code, notes, and snippets.

@mattroyer
Last active October 12, 2015 14:38
Show Gist options
  • Save mattroyer/4042464 to your computer and use it in GitHub Desktop.
Save mattroyer/4042464 to your computer and use it in GitHub Desktop.
Histogram App in Ruby
# Create a histogram of a string
#
# Example:
#
# > This is my phrase. Is it a cool phrase?
# #=> phrase 2
# is 2
# cool 1
# it 1
# my 1
# a 1
# this 1
#
# Output the string to the console.
puts "Give me a phrase, yo:"
# Get input from the user and store in
# a variable. Make the string lowercase
# so there can be more than one of the
# same word no matter what case it is.
text = gets.chomp.downcase
# Remove all punctuation marks from the
# string, so words are stored by themselves
# in the "words" array below.
text = text.gsub!(/[^A-Za-z ]/, '')
# Split input on spaces and create a variable
# holding that input in an array as separate
# words.
words = text.split(" ")
# Create a new hash with a default value to
# initialize it and assign it to a variable.
frequencies = Hash.new(0)
# Create a loop through the words array.
# For each entity in the array, assign the
# entity as a key in the hash and add 1 to
# every entity. If entities are the same,
# don't assign a key, but plus 1.
words.each { |word| frequencies[word] += 1 }
# Sort the frequencies hash by the values.
# This will sort them from 1, 2, 3, etc...
frequencies = frequencies.sort_by { |a, b| b }
# Reverse the hash so that the sort will
# be by values from highest to lowest:
# 4, 3, 2, etc...
frequencies.reverse!
# Loop through the frequencies hash and
# build a string to output to the console.
# Put the word first, followed by a space
# and the frequency count (value). Use .to_s
# to convert the value from an integer to a
# string.
frequencies.each { |word, frequency| puts "#{word} #{frequency.to_s}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment