mardi 3 janvier 2017

Ruby: Determining if an array includes any object from user input

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 predetermined list...she's prompted to try again, until she finally includes one of the predetermined words in her sentence.

I'm still a beginner and having trouble nailing this one down. Any help would be 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.

Aucun commentaire:

Enregistrer un commentaire