Reputation: 726
The idea is simple: If "red", "green", "orange", or "yellow" is input then Message passes.
The result I am getting is that it is failing. Also, I would like to randomly choose one color in the colors
array.
I believe using this would work:
colors = [].sample
colors = ["red", "green", "orange", "yellow", "blue", "purple"]
correct_guesses = ["red","green","orange","yellow"]
total_guesses = 10
print "Enter your guess: "
guess = gets.chomp
if correct_guesses.include?(colors)
puts "You got it right."
else
puts "You got it wrong. Guess again."
end
Upvotes: 1
Views: 78
Reputation: 15967
You're basically asking does any element of colors
equal the object correct_guesses
.
So on paper that looks like this:
does ["red", "green", "orange", "yellow", "blue", "purple"]
include the array ["red","green","orange","yellow"]
?
The answer is false. colors
is only one array of 6 string elements.
So what would pass as true
in this scenario? You could make it pass if colors
had a second array like this:
colors = [["red", "green", "orange", "yellow"], "blue", "purple"]
That is obviously problematic, now red, green orange & yellow are all coupled together, we need them to be in the same group or create other permutations in order make this pass.
That said, I think we all get what you're trying to do here. You're writing this as "does anything in the list correct_guesses
match anything in the list colors".
That inherently means we need to loop through each array in order to get that outcome.
if includes_any?(colors, correct_guesses)
puts "you are correct"
else
puts "you got it wrong"
end
Then you'd just write a function to make the check like this:
def includes_any(colors, correct_guesses)
correct_guesses.each do |guess|
return true if colors.include?(guess)
end
false
end
This example doesn't have anything to do with user input because you're original code seems to bypass the guess
variable so I omitted it as well.
Upvotes: 1
Reputation: 1939
What you want is to say is
if correct_guesses.include?(guess)
That will check if your guess is correct, by checking every element in the correct_guesses
array.
guess
is the variable that is assigned the value of what you are typing into the console.
This will also work
if correct_guesses.any?{|g| g == guess}
This will check if any element in the correct_guesses
array is equal to the value the user typed in.
Upvotes: 2