Ruby:确定数组是否包含来自用户输入的任何对象

时间:2017-01-03 09:07:11

标签: arrays ruby if-statement while-loop gets

编写一个提示用户输入句子的基本程序。

如果用户的句子中的任何单词与来自预定单词库的单词匹配,则程序退出该功能并移动到下一个单词。

但如果用户的句子中没有包含在单词库中的单词...则会提示她再次尝试,直到她最终在句子中包含一个预定单词。

在下面的代码中,当用户键入句子时,会出现以下错误消息:

test2.rb:14:in `<main>': undefined local variable or method `word' for main:Object (NameError)

我的问题是两个人:

  1. 为什么打印错误?
  2. 是否有更清晰,更简单的方法来编写同样的功能?
  3. 我还是初学者,所以你能提供的任何帮助都非常感激。提前谢谢!

    代码:

    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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果我清楚地了解您的问题,您可以使用此代码。

# 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