ruby · level 1 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
lets your program ask a question.
gets is like a waiter taking your order. Your program stops and waits while the person types an answer and presses Enter. Then gets hands back what they typed, as a string.
Show the question first with print, so the answer goes on the same line. Then store the answer in a variable: .
Pressing Enter leaves an invisible new line on the end of the answer. .chomp bites it off. Without it, anything you join after the answer drops onto the next line.
Leave a space at the end of your question, inside the quotes, so the answer does not bump into it.
guess first
Someone types crisps. What appears?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
print "Favourite snack? "
snack = gets.chomp
puts "Yum, " + snack
your turn
Your turn. Write the second question.
Write a question asking for a favourite food between the quotes on line 3. End it with a space. We will answer Sam and pancakes.
fix it
The ! fell off the end. Can you fix it?
- Run it. Why has the ! dropped onto a line of its own?
getskeeps the Enter key as a new line on the end of the answer. Something needs to bite it off.- Change line 2 to name = gets.chomp, then press run.
nailed it
your program asked and listened. :D
getswaits for an answer and hands it back as a string..chompbites the new line off the end.- Store the answer in a variable to use it later.
new words in your collection
- gets
- chomp
This lesson isn’t saved. A free account remembers every lesson you finish.