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

时间:2013-05-15 23:21:29

标签: 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) }.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
    }

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

3 个答案:

答案 0 :(得分:1)

我找到了一个很好的解决方案,它有点复杂:它将文件转换为字符串然后转换为数组,删除未打字的行,然后将数组打印回文件。我在一个真实的脚本中转换了你的一小段代码,找到了包含用户输入的行数,然后询问你是要删除它们还是仅删除其中一行。我带了一点把代码带到这个版本,但是我喜欢挑战(也许你现在笑了,想着“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.S。:它使用现场编辑,因此不建议用于大文件,它会占用你的资源。

P.P.S:我的脚本漫长而复杂,所以如果任何高级Ruby程序员想要改进我的脚本,欢迎他或她!

答案 1 :(得分:0)

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

答案 2 :(得分:0)

如果您在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算法'或者看看这个example code

如果这是某种家庭作业,那么这些建议都不可能。