How to specify output file encoding in Ruby?

17,707

Solution 1

Here's an example that outputs a file in the UTF-16LE encoding:

open("data.txt", "w:UTF-16LE")

Ruby looks at the encoding of the string you are writing, and transcodes as necessary. Here's a very detailed blog post describing mechanics with excellent examples (see the section called "The Default External and Internal Encodings").

Solution 2

That blog also has a bunch of great information about character encoding with Ruby, including a post about encoding with Ruby 1.8.

Solution 3

Here's the way to read pages with Japanese Shift JIS encoding:

  file = open(url, "r:Shift_JIS")
Share:
17,707
Fluffy
Author by

Fluffy

(your about me is currently blank) click here to edit

Updated on June 04, 2022

Comments

  • Fluffy
    Fluffy almost 2 years

    How can I set the encoding of a file when using a File#open?

  • Kelvin
    Kelvin about 12 years
    It's odd that this feature is still undocumented on ruby-doc.org.