I\'d like to add a single line to the top a of file with Ruby like this:
# initial file contents
something
else
# file contents after prepending \"hello\" o
No mechanism exists to do what you want to do easily.
Instead, you will need to open the file, delete the file, open a new file by the old name for writing, write your content, and then write the new file from the old file's contents. That's pretty convoluted sounding but is straightforward in code:
$ cat prepend.rb
#!/usr/bin/ruby
File.open("passwd", "r") do |orig|
File.unlink("passwd")
File.open("passwd", "w") do |new|
new.write "test string"
new.write(orig.read())
end
end
Note that the mechanism I've used doesn't bother checking errors -- you should probably handle errors on each File.open() request and the File.unlink() request -- and it assumes that the entire contents of the file will fit in memory. A short example:
$ rm passwd
$ cp /etc/passwd .
$ ./prepend.rb
$ head passwd
test stringroot:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
$
If you want to handle files that might not fit entirely in memory, you should code a loop sort of like this (untested -- better consider it pseudo-code):
while (data=orig.read(4096)) {
new.write(data)
}
As an alternative, you could write to a temporary file, and if the writing process succeeds, then delete the file and rename the temporary file in place. Whichever approach makes the most sense to you.