深度解析Ruby文件操作
创始人
2024-06-15 19:21:19
0

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

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文件操作的一些技巧。

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...