首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Ruby读取文件?

如何使用Ruby读取文件?
EN

Stack Overflow用户
提问于 2018-03-21 04:59:53
回答 2查看 0关注 0票数 0

我如何在Ruby中使用循环读取文件?

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

EN

Stack Overflow用户

发布于 2018-03-21 13:49:55

代码语言:txt
复制
#!/usr/bin/ruby -w

# Created by Michael Williams 12/19/2005
# Licensed under Create Commons Attribution License

示例1-读取文件并关闭:

代码语言:txt
复制
counter = 1
file = File.new("readfile.rb", "r")
while (line = file.gets)
    puts "#{counter}: #{line}"
    counter = counter + 1
end
file.close

示例2-将文件传递到块:

代码语言:txt
复制
File.open("readfile.rb", "r") do |infile|
    while (line = infile.gets)
        puts "#{counter}: #{line}"
        counter = counter + 1
    end
end

示例3-具有异常处理的读取文件:

代码语言:txt
复制
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
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100001479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档