Request Dev Services ยป

theDevTip.com

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"
contents=File.read(filename)

puts "Enter a noun: "
noun=gets.chomp

puts "Enter a verb: "
verb=gets.chomp

puts "Enter an adjective: "
adj=gets.chomp

puts "Enter an adverb: "
adv=gets.chomp

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

puts File.read(filename)

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

avatar
  Subscribe  
Notify of