Zisakis Zavitsanakis Zisakis Zavitsanakis - 1 year ago 62
Ruby Question

Ruby writes HEX in file instead of UTF8

i'm writing a fairly simple ruby script which follows the following procedure:

  1. Load 500 items from a json list

  2. Make a GET request for each one of them and process the data

  3. If the script exits (for few reason) remember the last item processed

The first 2 are done and they're working fairly well.

My problem is on the 3rd part. In order for my script to remember the last is processed im writing it in to a .txt file with the code below:

file = File.read('./Formating/Items.json')
last_key = File.open('./last.txt', 'r')
l = last_key.first(1)

data = JSON.parse(file)

puts l
data.each_with_index do |item, index|



The problem appears when im using the
command with the

Instead of deleting everything from the file and adding the new id as a plain text it adds the new id in HEX.

If i use
alone it will work. If i use
alone it will work. When im using them together im getting the HEX output.

When i'm reading the file it translates the HEX code to a UTF string and i could leave it like that but the problem is that instead of deleting the HEX content it appends the new id at the end, making the file larger.

Is there any way i can fix it?

Answer Source

I believe the problem is that you are truncating the file, that is currently open.

Quick blind untested fix, that must work:

file = File.read('./Formating/Items.json')
last_key = File.read('./last.txt').to_i rescue 0

data = JSON.parse(file)

puts "Last key is: #{last_key}"
data.each_with_index do |item, index|
    next if index <= last_key # skip already processed  
    # or: data.drop(last_key).each_with_index do |item, index|
    File.write('./last.txt', index.to_s)