`
DAOException
  • 浏览: 120876 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Ruby简单读取文件

    博客分类:
  • ruby
阅读更多

用于获取键盘输入,并输出

 

while line = gets
    puts line
end

 

 按照行读取文件内容

 

File.open("E:/workspaceNew/RubyStudy/test.txt") do |file|
file.each_line{|line| puts "Got #{line.dump}"}
file.close();
end

 

 按照行读取文件,并按照制定的字符串进行分割.本文中以e字母进行分割

 

File.open("E:/workspaceNew/RubyStudy/test.txt") do |file|
file.each_line("e"){|line| puts "Got #{line.dump}"}
file.close();
end

 

 使用IO.foreach读取文件

 

IO.foreach("E:/workspaceNew/RubyStudy/test.txt"){|line| puts line};

 

 可以将读取的文件保存在一个字符串当中

 

str = IO.read("E:/workspaceNew/RubyStudy/test.txt");
  puts str.length;
  puts str[0,30]

 

 也可以将读取的文件保存在一个数组当中

 

arr = IO.readlines("E:/workspaceNew/RubyStudy/test.txt")
puts arr.length;
puts arr[0]

 

 

分享到:
评论
1 楼 jmu 2012-02-09  


引用
    File.open("E:/workspaceNew/RubyStudy/test.txt") do |file|  
    file.each_line{|line| puts "Got #{line.dump}"}  
    file.close();  
    end  




file open block里面是不需要手动关闭file的

相关推荐

Global site tag (gtag.js) - Google Analytics