There is a Ruby string with the contents of a docx file (MS Office Word document).
You need to save it to a file. Under Windows.

The easiest way does not work:

File.write(filename, contents) 

The resulting file will not open. Why? How to solve it?

  • The question does not boil down to simply writing binary content to a file? - Nick Volynkin
  • I convert html to markdown then markdown to docx and this data needs to be written to a file. They have a different look than plain text with formatting, but maybe I'm doing something wrong. In this case, the data is not recorded in the simple way of the type open ('testfile.docx', 'w') {| f | f.puts @ converter.convert} - Igor Baranyuk
  • I solved the problem like this: file = File.new ("my_xml_data_file.docx", "wb") file.write (data) file.close - Igor Baranyuk

1 answer 1

There is a feature in Windows: the default files open in text mode, converting between \r\n (in the file) and \n (in Ruby) (in the output, as here; when you enter, there are still effects around Ctrl + Z / EOF, see option t ).

Therefore, when writing binary data to a file, it is necessary to explicitly specify b in the file open mode, for example ( c IO.write ; NB: File inherits IO ):

 File.write(filename, contents, mode: "wb") 

... otherwise, the bare byte 0A will be displayed as two bytes: 0D 0A , and the file will not exactly what was in the original line and it probably will not be read by the required software.

Written based on a comment by the author of the question .