Forum: Ruby Writing text files with an explicit encoding (UTF-16LE)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
51fe8139c227985278ff8d316650dc2f?d=identicon&s=25 Tim Perrett (tim-perrett)
on 2008-01-31 14:46
Hey all,

I cant seem to find any documentation on how to write a text file to the
filesystem with an explicit encoding type? Can someone point me in the
right direction? Its a simple text file, but it *needs* to be UTF-16.

Cheers

Tim
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2008-01-31 15:12
Tim Perrett wrote:
> Hey all,
>
> I cant seem to find any documentation on how to write a text file to the
> filesystem with an explicit encoding type? Can someone point me in the
> right direction? Its a simple text file, but it *needs* to be UTF-16.
>
> Cheers
>
> Tim

require 'iconv'

converter = Iconv.new("UTF-16", "ISO-8859-15")
utf_16_str = converter.iconv('hello world')
p utf_16_str

--output:--
"\376\377\000h\000e\000l\000l\000o\000 \000w\000o\000r\000l\000d"
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2008-01-31 16:11
7stud -- wrote:
>
> require 'iconv'
>
> converter = Iconv.new("UTF-16", "ISO-8859-15")
> utf_16_str = converter.iconv('hello world')
> p utf_16_str
>
> --output:--
> "\376\377\000h\000e\000l\000l\000o\000 \000w\000o\000r\000l\000d"

Whoops.  I overlooked the 'LE' in your title:

require 'iconv'

converter = Iconv.new("UTF-16LE", "ISO-8859-15")
utf_16_str = converter.iconv('hello world')
p utf_16_str

--output:--
"h\000e\000l\000l\000o\000 \000w\000o\000r\000l\000d\000"
51fe8139c227985278ff8d316650dc2f?d=identicon&s=25 Tim Perrett (tim-perrett)
on 2008-01-31 16:16
7stud -- wrote:
> require 'iconv'
>
> converter = Iconv.new("UTF-16", "ISO-8859-15")
> utf_16_str = converter.iconv('hello world')
> p utf_16_str
>
> --output:--
> "\376\377\000h\000e\000l\000l\000o\000 \000w\000o\000r\000l\000d"

So presumably something like the below would work?

converter = Iconv.new("UTF-16", "ISO-8859-15")
utf_16_str = converter.iconv('hello world')

File.open('example.txt', 'w') do |f|
   f.puts utf_16_str
end
51fe8139c227985278ff8d316650dc2f?d=identicon&s=25 Tim Perrett (tim-perrett)
on 2008-01-31 16:20
Yup - it works :)

Thanks!
This topic is locked and can not be replied to.