How to write BOM marker to a file in Ruby

I have some working code with a crutch to add BOM marker to a new file.

  #writing name, 'w', 0644 do |file|
    file.write "\uFEFF"
    file.write @data

  #reading name, 'r:bom|utf-8' do |file|

Is there any way to automatically add the marker without writing cryptic "\uFEFF" before the data? Something like name, 'w:bom' # this mode has no effect maybe?


  • Alas I think your manual approach is the way to go, at least I don't know a better way:

    To quote from JEG2's article:

    Ruby 1.9 won't automatically add a BOM to your data, so you're going to need to take care of that if you want one. Luckily, it's not too tough. The basic idea is just to print the bytes needed at the beginning of a file.