2016-10-18 11 views
0

私には援助が必要な学校の割り当てがあります。それはユーザーのための可能なものでなければならない値を入力して新しいファイルに保存し、ファイル内の値を検索する方法

  • アーティファクト
  • 仮定

:これらの値を保持することができ

Rubyプログラム: これは、割り当ての説明は次のとおりです。

  • これらの3つのタイプの値を入力します。
  • タイプアーティファクト、値、または前提の値を検索します。
  • プログラムは、ループと少なくとも1つのクラス定義を使用しなければならない。

私のために動作しません唯一の機能は、これらの行です:

f= File.new("Artefacts", "r") 
puts "Search for information regarding cultural information" 
userinput = gets.chomp 
if File.readlines("Artefacts").include?('userinput') 
    puts "We have found your input." 
else 
    puts "We have not found your input." 
f.close 

は何があってユーザーを挿入、それだけで「私たちはあなたの入力を見つけていません」と表示されません。

+0

はこの自分をデバッグしてみます。 1行のプログラム 'p File.readlines(" Artefacts ")を実行し、それが何を出力するかを見てください。また、 'p userinput'という行をプログラムの適切な場所に挿入して、ユーザー入力文字列の内容を確認してください。 –

+1

これは、 'byebug'のようなデバッガを試すのに適しています。コードにブレークポイントを入れ、実行時に変数をチェックすることができます。 –

+0

「[スマートウェイの質問方法](http://catb.org/esr/faqs/smart-questions.html)」を読むことをお勧めします。将来の質問に役立ちます。また、「[mcve]」と読むことをお勧めします。宿題の質問は、SOの面白い問題です。あなたの質問にもっと力を入れてデバッグすることを強くお勧めします。 "[どのくらいの研究努力がStack Overflowユーザーに期待されていますか?](http://meta.stackoverflow.com/q/261592)" –

答えて

0

パートA:ユーザー入力を取得し、

def write_to_file(path, string) 
    # 'a' means append 
    # it will create the file if it doesnt exist 
    File.open(path, 'a') do |file| 
     file.write string + "\n" 
    end 
    end 

    path = "Artefacts" 
    num_inputs = 3 
    num_inputs.times do |i| 
    puts "enter input (#{i + 1}/#{num_inputs}):" 
    write_to_file path, gets.chomp 
    end 

    puts `cat #{path}` 
    # if you entered "foo" for each input, 
    # this will show: 
    # foo 
    # foo 
    # foo 

パートBファイルに書き込め:ファイルを読み込み、それを文字列が含まれているかどうかを確認:

path = "./Artefacts" 
    query = "foo" 

    text = File.read path 
    # this will be a string with all the text 

    lines = File.readlines path 
    # this will be an array of strings (one for each line) 

    is_text_found = text.include? query 
    # or 
    is_text_found = lines.any? do |line| 
    line.include? query 
    end 
関連する問題