Ruby 如何从CSV文件中删除行

Ruby 如何从CSV文件中删除行,ruby,csv,Ruby,Csv,我想删除一行并写回文件 当我删除时,它会删除CSV文件的所有内容 products = {} def menu puts "#{'Item'.ljust(6)} #{'Description'.ljust(10)} #{'Price'.rjust(7)}" puts '-' * 4 + ' ' + '-' * 11 + ' ' + '-' * 5 File.open('text.txt').readlines.each do |itemnumber| puts itemnumbe

我想删除一行并写回文件

当我删除时,它会删除CSV文件的所有内容

products = {}


def menu
 puts "#{'Item'.ljust(6)} #{'Description'.ljust(10)} #{'Price'.rjust(7)}"
 puts '-' * 4 + '   ' + '-' * 11 + '   ' + '-' * 5
File.open('text.txt').readlines.each do |itemnumber|
puts itemnumber.gsub(/[,]/, '      ')
end
end

user_choice = 0
while user_choice !=8
 puts ''
 puts 'What would you like to do?'
 puts '1: View all products.'
 puts '2: Add a new product.'
 puts '3: Delete a product.'
 puts '4: Update a product.'
 puts '5: View highest priced product.'
 puts '6: View lowest priced product.'
 puts '7: View sum of all products prices.'
 puts '8: Exit.'
 user_choice = gets.chomp.to_i

 if user_choice == 1
  menu
 end


if user_choice == 2
puts ''
puts 'Enter new products description. '
new_products = gets.chomp
puts 'Enter new products price. '
price = gets.chomp.to_f
new_key = rand(100..999)
while products.has_key?(new_key)
  new_key = rand(100..999)
end
puts "#{new_key},#{new_products},#{price}"
open('text.txt', 'a') { |newproduct|
  newproduct.puts "#{new_key},#{new_products},#{price}"
}
end


if user_choice == 3
menu
puts ''
puts "What's the item number you wish to delete?"
item_num = gets.chomp

read_file = File.new('text.txt', "r+").read
write_file = File.new('text.txt', "w+")

read_file.each_line do |line|
  write_file.write(line) unless line.include? item_num
end
end

我做错了什么?在程序的“删除”部分,我肯定有多处错误

您的删除实际上正在进行,但您当前运行的应用程序尚未意识到这一点

您可以通过重新启动应用程序和/或查看文本文件来检查这一点

要解决此问题,在写入块中的文件结束后,请关闭文件以刷新更改:

read_file.each_line do |line|
  write_file.write(line) unless line.include? item_num
end
write_file.close