# File manipulation

**URL:** <https://www.ruby-forum.com/t/file-manipulation/91856>\
**Category:** Ruby\
**Created:** [April 12, 2007, 9:52pm UTC](https://www.ruby-forum.com/t/file-manipulation/91856 "2007-04-12T21:52:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![spacechurro](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/d2c977/32.png) [@spacechurro](https://www.ruby-forum.com/u/spacechurro)\
**Post date:** [April 12, 2007, 9:52pm UTC](https://www.ruby-forum.com/t/file-manipulation/91856/1 "2007-04-12T21:52:26Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![spacechurro](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/d2c977/32.png) [@spacechurro](https://www.ruby-forum.com/u/spacechurro)\
**Post date:** [April 13, 2007, 12:22am UTC](https://www.ruby-forum.com/t/file-manipulation/91856/2 "2007-04-13T00:22:21Z")

</div>

On Apr 12, 2:52 pm, Sergio R. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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 )  
}

---

<div class="post-metadata">

**Author:** ![spacechurro](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/d2c977/32.png) [@spacechurro](https://www.ruby-forum.com/u/spacechurro)\
**Post date:** [April 13, 2007, 4:25am UTC](https://www.ruby-forum.com/t/file-manipulation/91856/3 "2007-04-13T04:25:19Z")

</div>

> 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!
