# Output UTF-16LE BOM to file - 1.9

**URL:** <https://www.ruby-forum.com/t/output-utf-16le-bom-to-file-1-9/165182>\
**Category:** Ruby\
**Created:** [April 9, 2009, 10:32pm UTC](https://www.ruby-forum.com/t/output-utf-16le-bom-to-file-1-9/165182 "2009-04-09T22:32:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![chrismalek](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/6de8d8/32.png) [@chrismalek](https://www.ruby-forum.com/u/chrismalek)\
**Post date:** [April 9, 2009, 10:32pm UTC](https://www.ruby-forum.com/t/output-utf-16le-bom-to-file-1-9/165182/1 "2009-04-09T22:32:02Z")

</div>

ruby 1.9.1p0 (2009-01-30 revision 21907) [i386-mswin32]

With this code:

File.open(‘zz.txt’, ‘w:UTF-16LE’) do |f|  
f.print “Hello Uni-world”  
end

…I get no BOM

guts = File.read(‘zz.txt’)  
puts guts.bytes.to\_a.inspect

#=\> [72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0,…

…and my brain can’t concoct a way to insert it myself, though I know  
it must be simple…

---

<div class="post-metadata">

**Author:** ![chrismalek](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/6de8d8/32.png) [@chrismalek](https://www.ruby-forum.com/u/chrismalek)\
**Post date:** [April 12, 2009, 6:39pm UTC](https://www.ruby-forum.com/t/output-utf-16le-bom-to-file-1-9/165182/2 "2009-04-12T18:39:04Z")

</div>

On Apr 9, 2009, at 3:31 PM, Chris M. wrote:

> guts = File.read(‘zz.txt’)  
> puts guts.bytes.to\_a.inspect
> 
> #=\> [72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0,…
> 
> …and my brain can’t concoct a way to insert it myself, though I know  
> it must be simple…

Yeah, it’s easy stuff.

A Unicode BOM is just the character U+FEFF encoded at the beginning of  
the document. You can insert that character yourself with Ruby 1.9’s  
Unicode escape and it will be transcoded into the proper byte order  
based on the external\_encoding() you are writing to:

$ cat utf16\_bom.rb

# encoding: UTF-8

File.open(“utf16\_bom.txt”, “w:UTF-16LE”) do |f|  
f.puts “\uFEFFThis is UTF-16LE with a BOM.”  
end  
$ ruby -v utf16\_bom.rb  
ruby 1.9.1p0 (2009-01-30 revision 21907) [i386-darwin9.6.0]  
$ ruby -e ‘p File.binread(ARGV.shift)[0..9]’ utf16\_bom.txt  
“\xFF\xFET\x00h\x00i\x00s\x00”

Hope that helps.

James Edward G. II
