如何输入值,将它们保存到新文件并搜索文件中的值

时间:2016-10-18 20:32:12

标签: ruby search

我有一份我需要帮助的学校作业。 这是作业的描述:

可以保存这些值的Ruby程序:

  • 工件
  • 假设

用户应该可以:

  • 输入这三种类型的值。
  • 搜索Artifacts,Values或Assumptions类型的值。
  • 程序应使用循环和至少一个类定义。

唯一不适用于我的功能是:

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

无论用户插入什么,它都只显示“我们还没有找到您的输入”。

1 个答案:

答案 0 :(得分: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