Ask for More Letters
Learn how to use the loops and nested statements in Ruby.
We are going to extend the game also to do the following:
- Ask for a letter.
- Give feedback on the proposal.
- Ask for a letter again.
- Repeat these steps until the player enters the word “stop.”
Press + to interact
hidden_word = "hello"puts "_ _ _ _ _"putsloop doprint "Give me a letter: "answer = getsanswer = answer.chomp.downcaseif answer == 'stop'exitendif answer.length > 1puts "You must give only one letter!"elsif hidden_word.include?(answer)puts "The letter is part of the hidden word"elseputs "Invalid letter"endend
Loop implementation
We added loop do
at line 6 and end at line 25.
The do
and end
words, recognized by Ruby, surround a sequence of instructions called a block.
The effect of the loop
word is to repeat the execution of all the instructions inside the block, without ever stopping. The following diagram shows a simple ...