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

544 views Asked by At

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:

  1. Why is that error printing?
  2. 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.
2

There are 2 answers

0
Lukas Baliak On

If i clearly understand of your problem, you can use this code.

# define words
word_bank = %w(one two three four five)
# => ["one", "two", "three", "four", "five"]

# method to check words with bank
def check_words(answer, word_bank)
  # itterate over answer
  answer.each do |word|
    # if its include, return it out and print 'Great!'
    if word_bank.include?(word)
      puts 'Great!'
      return
    end
  end
  # not matched
  puts 'Nope!'
end

while true # infinite loop
  puts 'Type a sentence: '
  # get answer from the user
  answer = gets.chomp.downcase.split
  # get result
  check_words(answer, word_bank)
end
2
Abdullah On
word_bank = [
  "one",
  "two",
  "three",
  "four",
  "five" 
]
while true # total no of sentences(or functions)

  print "Type a sentence: "
  answer = $stdin.gets.chomp.downcase.split

  flag = false  
  idx = 0
  while idx < answer.length
    if word_bank.include?(answer[idx])
      flag = true
      print "Word matched successfully\n"
      break
    end
    idx += 1
  end

  if flag == true
    print "Great! Now type a second sentence: "    
  else
    print "Nope. Try again: "
  end
end