Exercise 11: Asking Questions

Now it is time to pick up the pace. You are doing a lot of printing to get you familiar with typing simple things, but those simple things are fairly boring. What we want to do now is get data into your programs. This is a little tricky because you have to learn to do two things that may not make sense right away, but trust me and do it anyway. It will make sense in a few exercises.

Most of what software does is the following:

  1. Take some kind of input from a person.
  2. Change it.
  3. Print out something to show how it changed.

So far you have been printing strings, but you haven't been able to get any input from a person. You may not even know what "input" means, but type this code in anyway and make it exactly the same. In the next exercise we'll do more to explain input.

print "How old are you? "
age = gets.chomp
print "How tall are you? "
height = gets.chomp
print "How much do you weigh? "
weight = gets.chomp

puts "So, you're #{age} old, #{height} tall and #{weight} heavy."


I use print instead of puts to print the string without a \n (newline) printed and the prompt stops right where the user should enter the answer.

What You Should See

$ ruby ex11.rb
How old are you? 39
How tall are you? 6'2"
How much do you weigh? 180lbs
So, you're 39 old, 6'2" tall and 180lbs heavy.

Study Drills

  1. Go online and find out what Ruby's gets.chomp does.
  2. Can you find other ways to use it? Try some of the samples you find.
  3. Write another "form" like this to ask some other questions.

Common Student Questions

How do I get a number from someone so I can do math?
That's a little advanced, but try gets.chomp.to_i which says, "Get a string from the user, chomp off the \n, and convert it to an integer."

Buy DRM-Free

When you buy directly from the author, Zed A. Shaw, you'll get a professional quality PDF and hours of HD Video, all DRM-free and yours to download.


Buy Directly From The Author

Or, you can read Learn Ruby the Hard Way for free right here, video lectures not included.