我如何使用Ruby读取文件?

我怎样才能读取一个文件,可能使用循环,在Ruby中?

请尽可能提供一些示例代码。

#!/usr/bin/ruby -w # Created by Michael Williams 12/19/2005 # Licensed under Create Commons Attribution License 

示例1 – 读取文件并closures:

 counter = 1 file = File.new("readfile.rb", "r") while (line = file.gets) puts "#{counter}: #{line}" counter = counter + 1 end file.close 

示例2 – 传递文件以阻止:

 File.open("readfile.rb", "r") do |infile| while (line = infile.gets) puts "#{counter}: #{line}" counter = counter + 1 end end 

示例3 – 使用exception处理读取文件:

 counter = 1 begin file = File.new("readfile.rb", "r") while (line = file.gets) puts "#{counter}: #{line}" counter = counter + 1 end file.close rescue => err puts "Exception: #{err}" err end