如何使用Ruby读取文件? [英] How can I read a file with Ruby?
本文介绍了如何使用Ruby读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果可能,请提供一些示例代码。
解决方案
#!/ usr / bin / ruby -w
#由Michael Williams创建12 / 19/2005
#在创建共享署名许可下授权
示例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)
put#{counter}:#{line}
counter = counter + 1
end
file.close
rescue => err
putsException:#{err}
err
end
How can I read a file, possibly using a loop, in Ruby?
Please provide some sample code if possible.
解决方案
#!/usr/bin/ruby -w
# Created by Michael Williams 12/19/2005
# Licensed under Create Commons Attribution License
Example 1 - Read File and close:
counter = 1
file = File.new("readfile.rb", "r")
while (line = file.gets)
puts "#{counter}: #{line}"
counter = counter + 1
end
file.close
Example 2 - Pass file to block:
File.open("readfile.rb", "r") do |infile|
while (line = infile.gets)
puts "#{counter}: #{line}"
counter = counter + 1
end
end
Example 3 - Read File with Exception Handling:
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
这篇关于如何使用Ruby读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文