class NullObject def method_missing (*args, &block) self end def nil?; true; end def to_str; end def to_ary; []; end end NULL_OBJECT = NullObject.new class SentenceGenerator def initialize(dictionary) @dictionary = dictionary @depth = @dictionary.depth end def random_word(last_word) @dictionary.dictionary.fetch(last_word, NULL_OBJECT).sample end def is_terminator?(symbol) (symbol =~ /[!?]/ || symbol == '.') end # Ugly way of making sure the key starts with a capital letter def random_capitalized_word random_choice = ["temp"] until random_choice[0] =~ /[A-Z]/ words = @dictionary.dictionary.keys random_choice = words[rand(words.length)] end random_choice end def generate_sentence() sentence = [] maximum_length = 20 wordcount = 0 sentence.concat(random_capitalized_word) until (is_terminator?(sentence.last[-1])) || wordcount > maximum_length wordcount += 1 word = random_word(sentence.last(@depth)) sentence << word end sentence.join(' ') end end