Embedding optional values into strings
1 2 NAMES=["Paul","Mac","Bimbo","a gamekeeper"] 3 NOUNS=["hat","monkey","lightbulb","fridge magnet","television"] 4 ADJECTIVES=["lively","hot","sneaky","elfin","average"] 5 6 def self.true?(chance) 7 (chance==0 or rand(chance)<1) 8 end 9 10 def self.build(string_array,chance=0) 11 true?(chance) ? string_array[rand(string_array.length)] : "" 12 end 13 14 def self.noun(chance=0) 15 build(NOUNS, chance) 16 end 17 18 def self.adjective(chance=0) 19 build(ADJECTIVES, chance) 20 end 21 22 def self.name(chance=0) 23 build(NAMES, chance) 24 end 25 26 def self.normalize(msg) 27 while msg.include?(" ") 28 msg.gsub!(/ /," ") 29 end 30 msg 31 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:
1 2 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.