如何使用用户输入从Ruby中的文件中删除字符串?

如何使用用户输入从Ruby中的文件中删除字符串?,ruby,file,Ruby,File,我知道如何根据用户输入搜索一个文件来定位一个特定的字符串,但我不知道一旦我找到了这个字符串,如何删除它。我见过各种grep方法,但不知道如何将它们更改为输入/输出,因此我得出以下结论: puts "Enter media to delete"; characters = gets.chomp; File.open("arraystarter.rb").each { |line| unless characters.each_char.map { |c| line.include?(c)

我知道如何根据用户输入搜索一个文件来定位一个特定的字符串,但我不知道一旦我找到了这个字符串,如何删除它。我见过各种grep方法,但不知道如何将它们更改为输入/输出,因此我得出以下结论:

puts "Enter media to delete";
characters = gets.chomp;

File.open("arraystarter.rb").each { |line| 
  unless characters.each_char.map  { |c| line.include?(c) }.include? false
    puts "Did you mean #{line}?";
  intent = gets.chomp.downcase
  case intent
  when 'yes'
  # TODO: Delete the line I've found
   puts "#{line} deleted!"
  when 'no'
  puts "Nevermind, then."
  end
  end
    }

我需要在“是”之后替换puts/“deleted”行,但是如何替换?

您会发现
sub('some text','')
或者您也可以使用
sub
来替换找到的一个或多个单词,根据您的需要,可以使用nil,有效地“删除”它。

如果您在UNIX机器上运行代码(Linux,Mac OS X)您可以在系统调用中作弊并使用sed命令

puts "Enter media to delete";
characters = gets.chomp;

system("sed s/#{characters}// arraystarter.rb > output.rb")
如果您需要在纯Ruby中运行此程序并使其具有高性能,请使用谷歌“Knuth–Morris–Pratt算法”或查看此程序


如果这是一种家庭作业练习,那么这两种建议都不是解决问题的方法。

我找到了一个很好的解决方案,它有点复杂:它将文件转换为字符串,然后转换为数组,删除未加修饰的行,然后将数组打印回文件ode,在一个真正的脚本中,找到多少行包含用户输入,然后询问您是否要删除所有行或其中一行。我花了一点时间将代码带到这个版本,但我喜欢challanges(也许您现在笑了,想“Challange?这是什么?”…对我来说这是一个挑战,因为我还有很多关于Ruby的知识要学。)希望这对我有所帮助

puts "Enter media to delete:"
characters = gets.chomp()
filename = "arraystarter.rb"
counts = 0

file_open = File.readlines(filename, 'rb')
file_to_string = file_open.map(&:inspect).join(',')
string = file_to_string.delete "\""
$array = string.split(/\\r/)
$array = string.split(/\\n/)

$array.map do |l|
  c = l.include? "#{characters}"
  counts += 1 if c == true
  next if c == true
end

def delete_all(characters)
  $array.each do |l|
  l.replace("") if l.include? characters
end
end

def puts_what(ct, l, c)
  if ct == 1 then puts "Did you mean #{l}?"
  else puts "#{c} exist in #{ct} lines. Do you want to delete all of them or just #{l}?" end
end

if string.include? "#{characters}"
  $array.each do |row|
  if row.include? "#{characters}" then puts_what(counts, row, characters)
    intent = gets.chomp()
    if intent == "yes"
      $array.delete row
      open_again = File.open(filename, 'w+')
      open_again.puts $array
      open_again.close()
      puts "#{row} deleted!"
      break
    elsif intent == "all"
      if counts == 1 then break end
      delete_all(characters)
      $array.delete ""
      open_once_more = File.open(filename, 'w+')
      open_once_more.puts $array
      open_once_more.close()
      puts "All the lines that contain #{characters} are deleted!"
      break
    elsif intent == "no" then puts "Never mind, then."
    end
  end
  end
else
  puts "Can't find #{characters}"
end
它100%完美地工作!这个脚本唯一的缺点是它总是在文件末尾留下一个空行,但是如果你没有问题,你可以很好地使用这个脚本

注意:它使用就地编辑,所以不建议对大文件使用,它会占用您的资源


p.p.S:我的脚本既长又复杂,因此,如果任何高级Ruby程序员想要改进我的脚本,他们都是受欢迎的!

您不能同时读取和写入文件。例如,您必须将文件读入数组,更改该数组,然后将其写回文件(如果文件很小)。