Last active
February 22, 2016 21:47
-
-
Save dpisarewski/2d841407b9c6dacbcab6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#original from http://stackoverflow.com/a/5452950/1305200 | |
def inplace_edit(filename) | |
File.open(filename, 'r+') do |file| | |
write_pos = 0 | |
file.each_with_index do |line, index| | |
eof = file.eof? | |
read_pos = file.pos | |
file.pos = write_pos | |
new_line = yield(line.chomp, index) | |
eof ? file.print(new_line) : file.puts(new_line) | |
write_pos = file.pos | |
file.pos = read_pos | |
end | |
file.truncate write_pos | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment