module Basher::Dictionary
Gives samples of random words as single instances or in batches. TODO: Extract constants to global configuration values. TODO: Allow words_list
to be a global config option / value.
Constants
- MAX_SIZE
Filter out words with more characters.
- MIN_SIZE
Filter out words with fewer characters.
- WORDS_LIST_PATH
Where is the words list path on the system. It is also assumed that there is only one word per line.
Public Instance Methods
grouped_words_list()
click to toggle source
Group words in the list by size.
# File lib/basher/dictionary.rb, line 36 def grouped_words_list @grouped_words_list ||= words_list.group_by(&:size) end
preload()
click to toggle source
Small utility function that preloads the words_list.
# File lib/basher/dictionary.rb, line 18 def preload !words_list.empty? end
random_word(size = MIN_SIZE)
click to toggle source
Returns a random word from the words file. The size argument must be greater than MIN_SIZE
.
size
- the size of the returned word.
# File lib/basher/dictionary.rb, line 26 def random_word(size = MIN_SIZE) # Return any word from the list if we supply size: nil return words_list.sample unless size grouped_words_list.fetch(size) do fail "Size must be in #{MIN_SIZE}..#{MAX_SIZE}" end.sample end
words_list()
click to toggle source
Returns an array of words, read from a file. Also caches the list.
# File lib/basher/dictionary.rb, line 41 def words_list @words_list ||= File.open(WORDS_LIST_PATH, 'r') do |file| file.each_line.lazy .map { |word| word.chomp.downcase } .select { |word| word =~ /\A[a-z]{#{MIN_SIZE},#{MAX_SIZE}}\z/ } .to_a end end