each_line
each_line调用blcok,并且把file的每一行传入block
File.open("testfile") do |file| file.each_line{|line| puts "got #{line}"} end ## "got line 1 \n" "got line 2 \n"
也可以给each_line传入参数来作为行分隔符
File.open("testfile") do |file| file.each_line("e"){|line| puts "got #{line}"} end ## "got line" " 1 \n" "got line" " 2 \n"
IO.foreach
它的作用和eachline 差不多
IO.foreach("testfile"){|line| puts line}
IO.read
把文件读进一个字符串
string = IO.read("testfile") string.length #=>60 string[1,20] # "sfdsdfsdfsdf..."
IO.readlines
把文件内容读入一个数组中(每行为一个元素)
arr = IO.readlines("testfile")