Forum: Ruby file manipulation

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fddbb3cd16868f4741c2e86ef015a639?d=identicon&s=25 Sergio T. Ruiz (sergio101)
on 2007-04-12 21:52
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
2ee1a7960cc761a6e92efb5000c0f2c9?d=identicon&s=25 William James (Guest)
on 2007-04-13 00:22
(Received via mailing list)
On Apr 12, 2:52 pm, Sergio Ruiz <ser...@village-buzz.com> wrote:
> right now, i know i am doing this in a kludgy way...
> is there a method that will just clear the file?
>     index_file.close
>   end
>
> --
> Posted viahttp://www.ruby-forum.com/.


File.open( 'index', 'r+') {|f|
  index = f.gets.to_i
  puts "Index value: #{ index }"
  f.rewind
  f.truncate(0)
  f.puts( index + 1 )
}
Fddbb3cd16868f4741c2e86ef015a639?d=identicon&s=25 Sergio T. Ruiz (sergio101)
on 2007-04-13 04:25
>
> 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!
This topic is locked and can not be replied to.