Search⌘ K

Ask for More Letters

Explore how to create an input loop in Ruby that repeatedly asks for a letter in the Hangman game. Understand loop structures, stopping conditions using 'stop', and how to validate user input to ensure only single letters are accepted. This lesson helps you manage repeated inputs and handle edge cases like empty entries effectively.

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.”
Ruby
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 snippet of code that would indefinitely display hello.

The arrows show that the block starts from the do word and lasts till the end word. It ...