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:

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