我为您的问题找到了非常好的解决方案,它有点复杂:它将文件转换为字符串,然后转换为数组,删除未处理的行,然后将数组打印回文件。我在一个真正的脚本中转换了您的一小段代码,该脚本查找有多少行包含用户输入,然后询问您是要全部删除还是只删除其中一个。我花了一点时间将代码带到这个版本,但我喜欢挑战(也许你现在笑了,想“挑战?这个?”....对我来说这是一个挑战,因为我还有很多事情要做了解 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% 完美运行!这个脚本唯一的坏处是它总是在文件末尾留下一个空行,但如果你对此没有任何问题,你可以使用这个脚本就好了。
PS:它使用就地编辑,因此不建议用于大文件,它会占用您的资源。
PPS:我的脚本又长又复杂,所以如果任何高级 Ruby 程序员想要改进我的脚本,欢迎他或她!