42

In ruby 1.9.x, we can specify the encoding with File.open('filename','r:iso-8859-1'). I often prefer to use a one-line File.read() if I am reading many short files into strings directly. Is there a way I can specify the encoding directly, or do I have to resort to one of the following?

str = File.read('filename')
str.force_encoding('iso-8859-1')

or

f = File.open('filename', 'r:iso-8859-1')
s = ''
while (line = f.gets)
    s += line
end
f.close
mu is too short
  • 426,620
  • 70
  • 833
  • 800
Chthonic Project
  • 8,216
  • 1
  • 43
  • 92

1 Answers1

67

From the fine manual:

read(name, [length [, offset]], open_args) → string

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

If the last argument is a hash, it specifies option for internal open().

So you can say things like this:

s = File.read('pancakes', :encoding => 'iso-8859-1')
s.encoding
#<Encoding:ISO-8859-1>
mu is too short
  • 426,620
  • 70
  • 833
  • 800