Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
file manipulation
Sergio Ruiz
4/12/2007 7:53:00 PM
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
--
Posted via
http://www.ruby-...
.
2 Answers
William James
4/12/2007 10:17:00 PM
0
On Apr 12, 2:52 pm, Sergio Ruiz <ser...@village-buzz.com> wrote:
> 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
>
> --
> Posted via
http://www.ruby-...
.
File.open( 'index', 'r+') {|f|
index = f.gets.to_i
puts "Index value: #{ index }"
f.rewind
f.truncate(0)
f.puts( index + 1 )
}
Sergio Ruiz
4/13/2007 2:25:00 AM
0
>
> 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!
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
file manipulation
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password