-1

i have a text file called text.txt with stored text like so

713,socks,3.99

888,hat,12.99

634,shirt,7.99

I want to open my file and choose a item number then i want to update the description and price. and save that back to the file.

heres my code so far

puts "Whats's the item number of the product you wish to update?"
item_num = gets.chomp
puts 'Enter new products description. '
new_description = gets.chomp
puts 'Enter new products price. '
new_price = gets.chomp.to_s
open('text.txt', 'r+') { |update|
update.puts "#{item_num},#{new_description},#{new_price}"
}
end

all this is doing is adding a new product with the same item number.

  • 1
    You have to read the _flat file_ and then write the updated one in a new file, and save the new file. This is how it works, – Arup Rakshit Mar 04 '15 at 05:08
  • Have a look at this question : http://stackoverflow.com/questions/3289653/how-to-modify-a-text-file-in-ruby – Gagan Gami Mar 04 '15 at 05:14
  • Do you really want the file to be in `CSV` itself? It may be easier to have it formatted as `YAML`. – Jikku Jose Mar 04 '15 at 06:24

1 Answers1

0

The easiest way to achieve a goal is to use CSV class to operate your file content. After all, the content is csv, right?

So, instead of:

open('text.txt', 'r+') { |update|
  update.puts "#{item_num},#{new_description},#{new_price}"
}

you might want to search for an element inside loaded array, update it and then write the content back to file:

require 'csv'
items = CSV.read("text.txt")
items.map! { |i| 
  next i unless i.first == item_num # skip unless it’s our item 
  i[1] = new_description
  i[2] = new_price
  i 
}

# here should go the code whether you need to insert line if `num` is not found

CSV.open("text.txt", "wb") do |csv|
  items.each { |i| csv << i }
end

This is definitely not a best production-quality code, the intent was to demonstrate how it’s to be done in general. Hope it helps.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160