Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created September 9, 2015 17:49
Show Gist options
  • Save mayfer/60999806364c8d9b0202 to your computer and use it in GitHub Desktop.
Save mayfer/60999806364c8d9b0202 to your computer and use it in GitHub Desktop.
require("./config.rb")
require("./file.rb")
class EssayStats
include FileReader
def initialize
@words = read_file(Config::ESSAY_PATH)
end
def num_words
@words.split(" ").length
end
end
es = EssayStats.new
puts es.num_words
module Config
DICT_PATH = "/usr/share/dict/words"
ESSAY_PATH = "/Users/murat/Code/LHL/modules/text"
end
module FileReader
def read_file(path)
File.open(path).read
end
end
require("./config.rb")
require("./file.rb")
class WordPlay
# pulls all the methods from the module as Instance Methods
include FileReader
# pulls all the methods from the module as Class Methods
# extend FileReader
def initialize
@words = read_file(Config::DICT_PATH)
end
def each_word
@words.each_line do |word|
word = word.strip
yield word
end
end
def find_palindromes(min_length)
each_word do |word|
if word == word.reverse && word.length >= min_length
puts word
end
end
end
def find_rhymes(rhyme)
each_word do |word|
# check if any of the words end in the rhyme
regex = /#{Regexp.quote(rhyme)}$/
if regex.match(word)
puts self.format_word(word)
end
end
end
def find_all_anagrams
anagrams = {}
each_word do |word|
signature = word.split("").sort.join
if !anagrams.has_key? signature
anagrams[signature] = []
end
anagrams[signature] << word
end
anagrams.each do |key, words|
if words.length < 3
anagrams.delete(key)
end
end
puts anagrams.inspect
anagrams.max_by do |signature, words|
words.length
end
end
end
wp = WordPlay.new
# wp.find_rhymes("rple")
# wp.find_palindromes(4)
puts wp.find_all_anagrams
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment