Hi,
I am trying to modify the file content in place. Here is my code :
file = File.open("#{Dir.pwd}/out1.txt", "r+")
s = file.gets
file.seek(0, IO::SEEK_SET)
file.puts s.strip
s = file.gets
file.seek(file.pos,IO::SEEK_SET)
file.puts s.strip
file.close
But, I am not getting the expected output. What I get is :
[arup@Ruby]$ cat out1.txt
foo
biz
[arup@Ruby]$ ruby a.rb
[arup@Ruby]$ cat out1.txt
foo
biz
[arup@Ruby]$
And I want it to be :
[arup@Ruby]$ cat out1.txt
foo
biz
Any hints to achieve this ?
···
--
Regards,
Arup Rakshit
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
Here's one way:
$ cat out1.txt
foo
bar
$ ruby -pli -e '$_.strip!' out1.txt
$ cat out1.txt
foo
bar
If you want to do it your way you need to remember read and write positions:
$ cat out1.txt >|x; cat x; echo @; ruby x.rb x; cat x
foo
bar
@
foo
bar
x.rb is:
File.open ARGV.shift, 'r+' do |io|
r_pos = w_pos = 0
while (io.seek(r_pos, IO::SEEK_SET); s = io.gets)
r_pos = io.tell
s.strip!
io.seek(w_pos, IO::SEEK_SET)
io.puts s
w_pos = io.tell
end
io.truncate(w_pos)
end
Cheers
robert
···
On Wed, May 6, 2015 at 9:43 PM, Arup Rakshit <aruprakshit@rocketmail.com> wrote:
Hi,
I am trying to modify the file content in place. Here is my code :
file = File.open("#{Dir.pwd}/out1.txt", "r+")
s = file.gets
file.seek(0, IO::SEEK_SET)
file.puts s.strip
s = file.gets
file.seek(file.pos,IO::SEEK_SET)
file.puts s.strip
file.close
But, I am not getting the expected output. What I get is :
[arup@Ruby]$ cat out1.txt
foo
biz
[arup@Ruby]$ ruby a.rb
[arup@Ruby]$ cat out1.txt
foo
biz
[arup@Ruby]$
And I want it to be :
[arup@Ruby]$ cat out1.txt
foo
biz
Any hints to achieve this ?
--
[guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can -
without end}
http://blog.rubybestpractices.com/