Embedding optional values into strings
NAMES=["Paul","Mac","Bimbo","a gamekeeper"] NOUNS=["hat","monkey","lightbulb","fridge magnet","television"] ADJECTIVES=["lively","hot","sneaky","elfin","average"] def self.true?(chance) (chance==0 or rand(chance)<1) end def self.build(string_array,chance=0) true?(chance) ? string_array[rand(string_array.length)] : "" end def self.noun(chance=0) build(NOUNS, chance) end def self.adjective(chance=0) build(ADJECTIVES, chance) end def self.name(chance=0) build(NAMES, chance) end def self.normalize(msg) while msg.include?(" ") msg.gsub!(/ /," ") end msg end
What does this all mean. Well, if you want to have conditional random words inserted into a sentence, for example if you are playing madlibs, or generating Fnords, all you have to do to generate the sentence is:
normalize("#{name} is a #{adjective(5)} #{adjective(2)} #{noun}.")
The numbers in brackets denote the odds of that part of speech being returned. This is used by the true? method to decide success or failure, and by the build method to determine whether a string or an empty string is returned. Finally, the normalize takes two spaces and replaces them with a single space.