Writing a basic program that prompts the user to type a sentence.
If any word from the user's sentence matches up with a word from a predetermined word bank, the program exits that function and moves onto the next one.
But if the user's sentence contains NO words that are included in the word bank...she's prompted to try again, until she finally includes one of the predetermined words in her sentence.
In the code below, when the user types a sentence, the following error message appears:
test2.rb:14:in `<main>': undefined local variable or method `word' for main:Object (NameError)
My question is a two-parter:
- Why is that error printing?
- Is there a cleaner, more simple way to write this same function?
I'm still a beginner, so any help you can offer is hugely appreciated. Thanks in advance!
Code:
word_bank = [
"one",
"two",
"three",
"four",
"five"
]
print "Type a sentence: "
answer = $stdin.gets.chomp.downcase.split
idx = 0
while idx < answer.length
if word_bank.include?(answer[idx])
next
else
print "Nope. Try again: "
answer = $stdin.gets.chomp.downcase.split
end
idx += 1
end
print "Great! Now type a second sentence: "
answer = $stdin.gets.chomp.downcase.split
#### ...and so on.
If i clearly understand of your problem, you can use this code.