Request Dev Services ยป

Simple Ruby mad lib w/ external include (intro programming tips)

Ah ha, so here we’ll use server-side Ruby to create a “Mad Lib” type program where we’ll pass prompted user input to dynamic placeholders through an external .txt include file. Neato!

filename = "story.txt"

puts "Enter a noun: "

puts "Enter a verb: "

puts "Enter an adjective: "

puts "Enter an adverb: "

if contents.include?('NOUN'){
   "\[NOUN\]" => noun,
   "\[VERB\]" => verb,
   "\[ADJ\]" => adj,
   "\[ADV\]" => adv
}.each do |key, value|
  contents.gsub!(key, value)
end, "w") { |f| f << contents }


Fyi, my /story.txt for this example, originally looks like this:

\n\nOnce upon a time on the internet...\n\n
      At a very reluctant [NOUN] I would sometimes [VERB] while being [ADJ] and [ADV] very fast (in Canada).

So, the above ‘story’ will be populated with the user inputs; i.e. [NOUN] will have the user inputted ‘[NOUN]‘ and so on and so forth. We now have a little program that prompts the user to input ‘nouns’, ‘adjectives’, and ‘adverbs’ and then invokes the user input into our story.txt include ‘mad lib’ story.

About the Author
Cameron Cashwell Web Developer
I build websites, web apps, and software. Wanna work together? Let's chat about your project!

Leave a Reply

Notify of