我如何在Ruby中使用循环读取文件?
请尽可能提供一些示例代码。
发布于 2018-03-21 13:49:55
#!/usr/bin/ruby -w
# Created by Michael Williams 12/19/2005
# Licensed under Create Commons Attribution License
示例1-读取文件并关闭:
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-具有异常处理的读取文件:
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
https://stackoverflow.com/questions/-100001479
复制相似问题