-1

I have a text file called text.txt, and it has the following text:

123,shirt,9.99 
234,pants,19.50
456,socks,3.99

How do I delete one row (e.g 123,shirt,9.99). How would I go about deleting this row?

My code so far:

 test_file = File.new('text.txt', "a")
 while (line = test_file)
   puts 'Enter the products item number you wish to delete. '
   user_delete = gets.chomp.to_i
   line.delete(user_delete)
 end
orde
  • 5,233
  • 6
  • 31
  • 33

2 Answers2

1

You're making a lot of mistakes here.

First of all opening the file with a (you need to use r+ or w+).

In Ruby we use a more elegant to iterate over files.

Check this answer, it will help you with your problem.

After that a look at IO library to understand how it all works

Community
  • 1
  • 1
Guilherme Carlos
  • 1,093
  • 1
  • 15
  • 29
1

I imagine there are a bunch of better ways to do this, but here's quick and dirty:

puts "What's the item number?"
item_num = gets.chomp

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

read_file.each_line do |line|
  write_file.write(line) unless line.include? item_num
end
orde
  • 5,233
  • 6
  • 31
  • 33