file manipulation

S

Sergio Ruiz

as a part of another program, i need to be able to keep an index number
inside of a file..

what i want to do is:

open the file
get its contents and store in a local variable
clear its contents
store an incremented version of the index..

right now, i know i am doing this in a kludgy way...

it works, but not pretty..

i end up opening the file 'r', getting the number
closing the file

opening it again 'w+'
storing the value
closing the file..

is there a method that will just clear the file?

my current code is:

def self.get_index
index_file = File.open('index','r')
index = index_file.gets
index_file.close
index_file = File.open('index','w+')
puts "index value: " + index.to_s
index_file.puts(index.to_i + 1).to_s
index_file.close
end
 
W

William James

as a part of another program, i need to be able to keep an index number
inside of a file..

what i want to do is:

open the file
get its contents and store in a local variable
clear its contents
store an incremented version of the index..

right now, i know i am doing this in a kludgy way...

it works, but not pretty..

i end up opening the file 'r', getting the number
closing the file

opening it again 'w+'
storing the value
closing the file..

is there a method that will just clear the file?

my current code is:

def self.get_index
index_file = File.open('index','r')
index = index_file.gets
index_file.close
index_file = File.open('index','w+')
puts "index value: " + index.to_s
index_file.puts(index.to_i + 1).to_s
index_file.close
end


File.open( 'index', 'r+') {|f|
index = f.gets.to_i
puts "Index value: #{ index }"
f.rewind
f.truncate(0)
f.puts( index + 1 )
}
 
S

Sergio Ruiz

File.open( 'index', 'r+') {|f|
index = f.gets.to_i
puts "Index value: #{ index }"
f.rewind
f.truncate(0)
f.puts( index + 1 )
}

perfect!

thanks so much!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,240
Messages
2,571,208
Members
47,845
Latest member
vojosay

Latest Threads

Top