2017-01-03 4 views
-1

ユーザーに文章の入力を促す基本プログラムを書く。Ruby:配列にユーザー入力のオブジェクトが含まれているかどうかを調べる

ユーザの文からの単語が所定の単語バンクからの単語と一致すると、プログラムはその機能を終了し、次の単語に移動する。

しかし、単語バンクに含まれている単語がユーザーの文に含まれていない場合、最終的に文章に所定の単語の1つが含まれるまで、再度試してみるように求められます。以下のコードで

、ユーザーの種類文は、次のエラーメッセージが表示されます。

  1. なぜそのエラー印刷は次のとおりです。

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

    私の質問は、二区分けのですか?

  2. この同じ機能をより簡単に作成する方法はありますか?

私はまだ初心者ですから、あなたが提供できるヘルプは非常に高く評価されています。前もって感謝します!

コード:

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. 
+1

質問がありますか? –

答えて

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 
+0

'if flag == true'を使う理由をTrueClass/FalseClassに設定すると' if flag'とBTWを使うことができるので 'puts flag? ":いいえ、今度は2番目の文を入力してください:": "いいえ、もう一度やり直してください:" ' –

+0

はい、あなたは正しいですが、質問者が初心者です。あなたのために+ 1コメント。 – Abdullah

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 
関連する問題