read file with one line of code 01. Jul 2008

There are probably at least a have a dozen ways to print the contents of a file in Ruby, here I will present four ways of doing it.

The first method is rather verbose. Assign a file object and iterate on the file object with the each_line method and then close the file.

f = open('file.txt')
f.each_line do |line|
  puts line
end
f.close

The second method still assigns a file object, but then uses the more compact readlines instance method and closes the file.

f = open('file.txt')
puts f.readlines
f.close

The third method uses block form to access the file and automatically close it.

open('file.txt') { |f| puts f.readlines }

The fourth method calls the class method readlines to wrap it all up in one statement.

puts File.readlines('file.txt')
 

Kommentare (2)

Kommentar schreiben

Markdown Syntax