Introduction To Ruby
Story Program


The story in this example is going to be based on the following text,

Once there was a adjective boy called name.

He went to place to buy a object.

The four words in bold will be the variables in this program. Our program will replace the bold words with words entered by the user of our program. Our program has to store the words that the user enters.


Here is the basic code to produce the story.

# Story Program

print "Enter a boy's name: "
name = gets.chomp
print "Enter an adjective: "
adjective = gets.chomp
print "Enter a place name: "
place = gets.chomp
print "Enter the name of an object: "
thing = gets.chomp

puts ""
story = "Once there was a #{adjective} boy called #{name}.
He went to #{place} to buy a #{thing}"
puts story


Study the example carefully. Notice how we make variables equal to gets.chomp. The input statement is actually gets, we've been using it in all of the examples so far. The .chomp part takes off the line break that is included in the value we get from gets. If you remove some of the .chomps from the code, you can see the effect of the method.

You can also see how we can include the variables inside the double-quoted strings if we enclose it inside #{ }.

An alternative way to achieve the same effect is to use the + operator to add the variables to the strings. The first part of the story could have been constructed with a line like,

story = "Once there was a "+ adjective + " boy called " + name + "."


  1. Write a program that asks the user to enter their name. Output some text that gives them an appropriate greeting.
  2. Although the code is pretty simple, you can still make something that can entertain. Look at how the story was written out in the introduction. Write a story or find some text and then underline some of the words. Adapt the program to ask the user to input alternatives to those words without giving away what the story will be like. The unpredicatability of the user's input and its effect on the finished story is what counts.