深度解析Ruby文件操作

开发 开发工具
Ruby文件操作对于一个经验丰富的编程人员来说是比较容易掌握的技巧。通过这篇文章,我们可以学到关于Ruby文件操作的一些技巧。

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

责任编辑:曹凯 来源: 百度博客
相关推荐

2009-12-16 11:04:51

Ruby操作文件权限

2010-04-14 15:32:18

Unix操作系统

2009-12-16 10:49:42

Ruby操作二进制文件

2009-12-18 16:27:41

Ruby解析Json

2009-12-18 15:56:05

Ruby特殊语法

2009-12-15 15:55:43

Ruby模块

2009-12-17 17:37:42

Ruby on Rai

2009-09-01 10:28:38

C#追加文件

2009-12-15 13:59:42

Ruby对象操作

2009-06-22 13:40:00

RubyJava

2009-09-01 10:10:51

C# StreamRe

2024-01-11 12:14:31

Async线程池任务

2009-12-17 13:57:15

Ruby关键字

2009-12-14 16:26:40

Ruby复制文件

2009-12-16 10:57:16

Ruby文件锁

2009-12-21 11:19:50

WCF配置文件

2009-12-18 16:00:29

Ruby获取当前类名

2010-04-22 13:56:21

Aix操作系统

2023-10-10 11:02:00

LSM Tree数据库

2023-03-27 08:12:40

源码场景案例
点赞
收藏

51CTO技术栈公众号