Jacob Moore Jacob Moore - 30 days ago 5
Ruby Question

Hangman game with a bug in my choice method

Excuse my global variables, this is a Hangman project I am working on. Everything is working as it should except for one part of this method.

def choice(n)
$random_word2.each_with_index do |i,index|
if i == n
$cipher[index] = i
end
end
if n == $random_word
puts "You win"
end
if $random_word2.include?(n) == false
$counter -= 1
display
puts "incorrect guess"
end
puts $cipher.join
end


Specifically these lines. As it is the program will print out $random_word so you will know what it is since it is random. If you type the whole word it should print "You win!" but instead it skips to the last "if" and accepts it as a incorrect guess. I tried different variables and it works, so that leads me to believe that the $random_word variable changes to a different random word at some point? I am lost, it prints the word, I type in the exact same thing and somehow it's not == .

if n == $random_word
puts "You win"


this is the whole program.

load 'display.rb'

class Hangman
attr_accessor :name
@name = name

def initialize
puts "What is your name?"
@name = gets.chomp
puts "
################################################
HANGMAN
################################################

_________
|
| |
| O
| /|\\
| |
| / \\
|
-----------------
Welcome #{@name} to Hangman. The computer will generate
a 5-12 letter random word. You will try to guess
that word one letter at a time. Try to solve the
puzzle before time runs out!


"
Gameplay.new
end
end

class Gameplay
def initialize
$array = []
File.foreach('5text.txt') do |x| $array << x if (x.chomp.length >= 5 and x.chomp.length <= 12) end
$random_word = $array.sample
$random_word2 = $random_word.split(//)
puts $random_word2.join
$cipher = $random_word.gsub(/[a-z]/, '*').split(//)
puts $cipher.join

def choice(n)
$random_word2.each_with_index do |i,index|
if i == n
$cipher[index] = i
end
end
if n == $random_word2.join.to_s
puts "You win"
end
if $random_word2.include?(n) == false
$counter -= 1
display
puts "incorrect guess"
end
if $counter == 0
puts "you lose!!!!!!"
puts "would you like to start another game? Y/N"
new_game = gets.chomp
if new_game == "Y"
Hangman.new
end
end
puts $cipher.join
end


$counter = 5
while $counter > 0
choice(gets.chomp)
end
end
end
Hangman.new

Answer Source

Change to

File.foreach('5text.txt') do |x|
  chomped = x.chomp
  $array << chomped if (chomped.length >= 5 and chomped.length <= 12)
end

Because the words have a \n not chomped in your origin program.