Hi, everyone. I am new to Ruby. I am trying to write a hangman programme where a user is presented with is presented with blanks. As they correctly guess a letter, the letter will replace the blank. I have written most of the programme, but cannot work out how to replace the blank with the correctly guessed letter. Can anyone help with this please? Code pasted below, thank you.
The purpose of the programme is to enable the blanks to be
replaced by each correctly guessed letter
word = “hello”
display_word = “”
word.size.times do
display_word += "_ "
end
display_word = display_word.split
guess = “h”
display_word.each_index do |letter, index|
if letter == “_” && word[index] == guess
display_word[index] = guess
end
end
Notice the // regexp at the end, to split the spaces. (Not giving an argument to split means it uses the value of $; which is probably not what you want! See class String - RDoc Documentation )
Incidentally, you could save yourself some trouble by making display_word an array to start with:
Thank you. This has been really helpful, and I have figured out how to replace a single instance of a letter and I am now working out how to replace multiple occurrences of the same letter, eg “l”.
word = ‘hello’
display_word = []
word.size.times do
display_word << "_ "
end
guess = ‘h’
if word.include?(guess)
correct = word.index(guess)
display_word[correct] = guess
end
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.