所以这就是我想做的事。
我正在尝试完成,所以每次运行时都会将字母变量添加到数组中。问题是,变量字母不断重写,循环再次运行。因此,如果我键入“g”,因此变量字母为“g”,它会将该变量放入数组中,然后再次运行它并重复此过程。所以在循环运行5次后,我希望数组为[l,g,e,f,g]。但相反它每次都被替换,而不是数组[l,g,e,f,g],它只是[g]因为变量字母当前是什么。
def checkLetter(word)
x = 0
while x < 5 do
puts "Enter a letter"
letter = gets.chomp.to_s
if word.include?(letter) == true
puts "The letter is in it"
allLetters = []
allLetters << letter
end
if word.include?(letter) == false
puts "Try again"
#add body part
end
x = x + 1
end
puts allLetters.inspect
end
puts "enter a word"
word = gets.chomp
checkLetter(word)
答案 0 :(得分:1)
您需要将allLetters = []
移出循环
def checkLetter(word)
x = 0
allLetters = [] # look here
while x < 5 do
puts "Enter a letter"
letter = gets.chomp.to_s
if word.include?(letter) == true
puts "The letter is in it"
allLetters << letter
end
if word.include?(letter) == false
puts "Try again"
#add body part
end
x = x + 1
end