jackpot
jackpot

Reputation: 23

How do i get it so the array keeps building not so it is replaced each time?

so here is what i want to do.

I am trying to accomplish so the letter variable gets added to the array each time it runs. The issue is, the variable letter keeps getting re written overtime the loop runs again. So if i type “g” so the variable letter is “g”, it'll put that variable in the array then run it again and repeat there process. So after the loop run 5 times, i want the array to be [l,g,e,f,g]. But instead it gets replaced everytime so instead of array being [l,g,e,f,g], its just [g] cuz thats what the variable letter is currently.

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)

Upvotes: 0

Views: 41

Answers (1)

Ryan-Neal Mes
Ryan-Neal Mes

Reputation: 6263

You need to move allLetters = [] outside of your loop

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

Upvotes: 1

Related Questions