Replacing blank character in array with a letter

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

but cannot work out how to replace the blank with the correctly guessed letter.

Your line display_word[index] = guess is the right idea.
Your problem is that display_word is not what you are expecting.

Try in irb:

2.7.1 :001 > word = "hello"
2.7.1 :002 > display_word = ""
2.7.1 :003 > word.size.times do 
2.7.1 :004 >   display_word += "_"
2.7.1 :005 > end
 => 5 
2.7.1 :006 > display_word = display_word.split
2.7.1 :007 > display_word
 => ["_____"] 
2.7.1 :008 > display_word.size
 => 1 

Your issue is with split, notice:

2.7.1 :009 > "   ".split
 => [] 
2.7.1 :010 > "   ".split //
 => [" ", " ", " "] 

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 https://docs.ruby-lang.org/en/2.7.0/String.html#method-i-split )

Incidentally, you could save yourself some trouble by making display_word an array to start with:

2.7.1 :012 > display_word = []
2.7.1 :013 > word.size.times do 
2.7.1 :014 >   display_word << " "
2.7.1 :015 > end
 => 5 
2.7.1 :016 > display_word
 => [" ", " ", " ", " ", " "]

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.

| Privacy Policy | Terms of Service | Remote Ruby Jobs