Ruby文件操作是一个比较常用的一个编程方法。在接下来的这篇文章中我们将会为大家详细介绍有关Ruby文件操作的一些实现技巧。#t#

创新互联-专业网站定制、快速模板网站建设、高性价比伊美网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式伊美网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖伊美地区。费用合理售后完善,十余年实体公司更值得信赖。
Ruby文件操作代码示例如下:
#2.rb;在同一级目录建立1.txt的文件,输入一些内容
file=File.open("1.txt","r")#file=File.open("F:\\ruby\\rb\\1.txt","r")绝对路径下
 file.each_line do |line|
 puts line
 end
# another logic
File.open("1.txt","r") do |file|
 while line=file.gets
 puts line
 end
 end
# the third logic ,the code is copied from someone else ...
IO.foreach("1.txt") do |line|
 #puts line if line =~/target/ 
 puts line if line !~/target/ 
 end
#count the number of a file ,the bytes and lines
arr=IO.read("1.txt")
 bytes=arr.size
 puts "the byte size is #{bytes}"
 arrl=IO.readlines("1.txt")
 lines = arrl.size
 puts"the lines number is #{lines}"
#show the file's path
puts File.expand_path("1.txt")
#count chars from a file
 file= File.new("1.txt")
 w_count = 0
 file.each_byte do |byte|
 w_count += 1 if byte ==?1
end
 puts "#{w_count}"
#create new file and write some words there
file= File.new("2.txt","w")
puts File.exist?("2.txt")#judge the file is exist or not
 file.write("hehe\nhahah")
#io.stream operation
require 'stringio'
ios = StringIO.new("abcdef\n ABC \n 12345")
 ios.seek(5)
 ios.puts("xyz3")
 puts ios.tell
puts ios.string.dump
#the result is 10,insert xyz3 at the 5th byte
#another example
require 'stringio'
ios = StringIO.new("abcdef\n ABC \n 12345")
 ios.seek(3)
 ios.ungetc(?w) #replace the char at index 3
puts "Ptr = #{ios.tell}"
 s1 = ios.gets #filte the "\n" 
 s2 = ios.gets
 puts s1
 puts s2
希望上面这段代码示例可以帮助我们熟练掌握Ruby文件操作的一些技巧。
                分享题目:深度解析Ruby文件操作
                
                文章来源:http://www.csdahua.cn/qtweb/news31/515281.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网