Read entire file: Difference between revisions

No edit summary
Line 431:
<pre>Lorem ipsum dolor sit amet, consectetur adipiscing elit nullam.</pre>
 
The encoding canis alsoUTF-8 by default, but it can be explicitly specified:
 
<lang ruby>content = File.read("input.txt", "UTF-16")</lang>
Line 441:
File.open allows for more options and closes the file implicitly. Combine it with File#gets_to_end to read the entire file:
 
<lang ruby>content = File.open("input.txt", mode: "r", encoding: "UTF-8") do |file|
file.gets_to_end
end</lang>
Line 447:
Or no implicit closing at all with File.new:
 
<lang ruby>file = File.new("input.txt", mode: "r", encoding: "UTF-8")
content = file.gets_to_end
file.close</lang>