I am trying to figure out a way to filter two arrays into one based on guessing the letters within one o them.. so basically hangman. But if I had
word_array = ["b", "u", "s", "b", "o", "i"]
hidden_array = Array.new(word_array.length, "-")
p hidden_array
I would want to then print to the console ["b", "-", "-", "b", "-", "-"] if "b" were guessed. What would be a good beginner way to create this array that will change over time? Should it maybe be a hash? Thanks!
All of the solutions so far revolve around arrays, but don't forget a string is basically a character array anyway. Just use strings:
word = 'busboi'
guesses = 'bs'
word.tr('^'+guesses, '-')
# => "b-sb--"
The String#tr method converts all letters in the first argument to the mapping in the second argument, so you can do things like ROT13, simple cyphers and such, or in this case use the negation feature ^ to invert the first set and replace all non-matching characters.
You can keep track of the found letters in an array and make a method to do the printing
word_array = ["b", "u", "s", "b", "o", "i"]
found_letters = []
def hangman_prompt(found_letters)
word_array.map do |char|
found_letters.include?(char) ? char : "-"
end.join(" ")
end
Then you could use this in an input loop like so:
loop do
puts hangman_prompt(found_letters)
puts "what is your guess?"
input = gets.chomp
if word_array.include? input
found_letters << input
end
end
I'm using Array#map here which creates a new array of the same length. Each of the original array items are passed to the block, which determines how they could be copied to the new array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With