如何使用Ruby读取文件?

时间:2021-11-15 05:10:13

How can I read a file, possibly using a loop, in Ruby?

如何在Ruby中读取文件(可能使用循环)?

Please provide some sample code if possible.

如果可能,请提供一些示例代码。

2 个解决方案

#1


96  

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

Example 1 - Read file and close:

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

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:

示例2 -将文件传递给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:

示例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

#2


576  

contents = File.read('filename')

http://www.ruby-doc.org/core-1.9.3/IO.html#method-c-read

http://www.ruby-doc.org/core-1.9.3/IO.html method-c-read

#1


96  

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

Example 1 - Read file and close:

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

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:

示例2 -将文件传递给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:

示例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

#2


576  

contents = File.read('filename')

http://www.ruby-doc.org/core-1.9.3/IO.html#method-c-read

http://www.ruby-doc.org/core-1.9.3/IO.html method-c-read