Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Embedding optional values into strings

I recently wrote a sentence generator, and one of the techniques I worked out might be useful to other people. The full detail is here, but the short version is:

   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.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS