Opens a file as a string and writes back the string to the file at the end of the block.

Returns the number of written bytes or nil if the file wasn’t modified.

Note that the file will even be written back in case the block raises an exception.

Mode can either be "b" or "+" and specifies to open the file in binary mode (no mapping of the plattform’s newlines to "\n" is done) or to append to it.

Usage

  # Reverse contents of "message"
  File.open_as_string("message") { |str| str.reverse! }

  # Replace "foo" by "bar" in "binary"
  File.open_as_string("binary", "b") { |str| str.gsub!("foo", "bar") }