flanelman flanelman - 29 days ago 7
Ruby Question

Ruby - Until loop doesn't seem to be working correctly

Hey guys I'm new to Ruby so apologies if this seems like a stupid question, just can't seem to figure out what I've done wrong.

I've struggled looking online for help too not really sure what to search without writing a novel about the issue.

The purpose of the code is to keep asking the user for input, until they enter a letter, I do this by checking if the users input is in the array "alphabet" and when they do so it should check it against "word" to check if the letter is within the word that I randomly select elsewhere (i'm trying to code hangman, just for context)

here's the code:

def Check_Alph(word)
until $alphabet.include? 'guess' == true
puts "Please guess a letter from the alphabet"
guess = gets.chomp
puts "#{guess}"
end

if $alphabet.include? 'guess' == true
puts "valid letter entered, checking.."
$guessed_Letters << guess
if word.include? 'guess' == true
puts "good guess! That letter was in the word!"
puts "Letters confirmed to be in word: #{correct_Letters}"
end
end
end


In the console, it just comes up "Please guess a letter from the alphabet" then when I enter a letter, it just re asks the question. I even tried outputting "guess" to check it was getting the value correctly and it was so not really sure what's going on.

Any help would be greatly appreciated!

Edit:

def Check_Alph()
guess == nil
until $alphabet.include?(guess)
puts "Please guess a letter from the alphabet"
guess = gets.chomp
puts "#{guess}"
end
end

Answer

There are two problems.

First the variable guess is not the same as the string 'guess'. But you check if $alphabet includes the string, not the value of the variable.

Second $alphabet.include? 'guess' == true leads to an error, because == has a stronger binding than the method call. Ruby reads that line like this $alphabet.include?('guess' == true). Since 'guess' or the variable guess will never equal true, it is the same as $alphabet.include?(false).

As others already pointed out there is no need to check for == true at all, because include? already returns a boolean.

Change

until $alphabet.include? 'guess' == true 

to

until $alphabet.include?(guess)

Furthermore you will need to define guess before you start the until block, otherwise it will be an unknown and raise an error. Just insert

guess = nil

to the top of your method.