Skip to content

Instantly share code, notes, and snippets.

@jtallant
Created September 22, 2012 01:44
Show Gist options
  • Save jtallant/3764829 to your computer and use it in GitHub Desktop.
Save jtallant/3764829 to your computer and use it in GitHub Desktop.
Obfuscate words and report frequency
# If this were for purposes of cleaning out
# offensive words it would be easier to just use gsub
# but in this case we want to preserve things like "bigger"
# when searching for "big"
# also the challenge was using an array as the second argument
# where this takes an unlimited number of params. Each param passed
# after the first is a string we want to obfuscate
# Alternative solution below that allows the words param to be
# an array or a string. If passing words in string form
# they should be space seperated.
# Replace words = words.to_a
# with words = words.split(' ') if !words.is_a?(Array)
# Remove the * from the words param
def obfuscate(phrase = '', *words)
words = words.to_a
phrase = phrase.split(' ')
words.each do |word|
phrase.collect {|item| item.replace('*' * item.length) if item.downcase == word.downcase}
end
phrase.join(" ")
end
def report(phrase = '', *words)
words = words.to_a
phrase = phrase.split(' ')
matches = []
occurrences = Hash.new(0)
words.each do |word|
phrase.collect {|item| matches << item if item.downcase == word.downcase}
end
matches.each do |match|
occurrences[match.downcase] += 1
end
occurrences
end
require 'test/unit'
require './obfuscate.rb'
class TestObfuscate < Test::Unit::TestCase
@@string1 = 'big string of big words is bigger'
@@result1 = '*** string of *** ***** is bigger'
@@result1_hash = { 'big' => 2, 'words' => 1 }
@@string2 = 'This is a comment from an asshole that likes to say fuck a lot. Go FUCK yourself'
@@result2 = 'This is a comment from an ******* that likes to say **** a lot. Go **** yourself'
@@result2_hash = { 'fuck' => 2, 'asshole' => 1 }
def test_obfuscate
assert_equal(@@result1, obfuscate(@@string1, 'big', 'words'))
assert_equal(@@result2, obfuscate(@@string2, 'fuck', 'asshole'))
end
def test_report
assert_equal(@@result1_hash, report(@@string1, 'big', 'words'))
assert_equal(@@result2_hash, report(@@string2, 'fuck', 'asshole'))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment