myfile = File.open(‘extrainfo.txt’)
cuid = myfile.readline
You better change that to
cuid = File.open(‘extrainfo.txt’) {|myfile| myfile.readline}
or if you want to get fancy even
cuid = File.open(‘extrainfo.txt’, &:readline)
Background is that this way the file is properly closed under all
circumstances.
You got solutions for the addition issue already. Of course you can
combine that on one line if you need:
cuid = Integer(File.open(‘extrainfo.txt’, &:readline)) + 1
If you need to write the new id back to the file you need to open the
file in read write mode. If you want to increment per each run you
can do something like this:
File.open(‘extrainfo.txt’, ‘r+’) do |io|
id = io.gets.to_i
puts id
io.seek(0)
io.puts(id + 1)
io.truncate(io.tell)
end
Note though that this is not safe for concurrent updates.
Kind regards
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.