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 "_ _ _ _ _"
puts
loop do
print "Give me a letter: "
answer = gets
answer = answer.chomp.downcase
if answer == 'stop'
exit
end
if answer.length > 1
puts "You must give only one letter!"
elsif hidden_word.include?(answer)
puts "The letter is part of the hidden word"
else
puts "Invalid letter"
end
end

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 ...