Home>

In general, when trying to replace the contents of a file with ruby ​​

# Open the file read-only and assign the contents to buffer
    buffer = File.open (path, "r") {| f | f.read ()}
    # convert the contents of buffer
    buffer.gsub! (@ pattern, @replacement)
    # write buffer to original file
    File.open (path, "w") {| f | f.write (buffer)}
I think it is often written like

, but is there no way to make this replacement part exclusive?

This closes when the block is closed, so it will be unlocked even if it is locked withf.flock (File :: LOCK_EX).

If a file is written between read and write, I think that it will be updated incorrectly with data that is not the latest.

I haven't thought of it, so I asked a question.