er,writer) do |reader,writer| # writer.close_write str = reader.gets reader.close end thread2 = Thread.new(reader,writer) do |reader,writer| # reader.close_read writer.puts("What hath God wrought?") writer.close end thread1.join thread2.join puts str # What hath God wrought?
4 使用非阻塞 IO ruby 会在后台执行一些操作, io 不会被阻断, 使 因此大部分情况下可以使用 ruby 线程来管理 IO,当一个线程被 Io 阻塞之 后,另外的线程能够继续执行. 由于 ruby 的线程不是一个 native 的线程,因此 ruby 的线程都在同一个进程里 面. 如果你想关闭一个非阻塞 io,你可以这样做: 代码: 代码: require 'io/nonblock' # ... test = mysock.nonblock? mysock.nonblock = true # ... mysock.nonblock = false # false # turn off blocking # turn on again
mysock.nonblock { some_operation(mysock) } # Perform some_operation with nonblocking set to true mysock.nonblock(false) { other_operation(mysock) } # Perform other_operation with non-blocking set to false
5 使用 readpartial readpartial 被
设计来用于就像 socket 这样的流. readpartial 要求提供最大长度的参数,如果指定了 buffer,那么这个 buffer 应指向用于存储数据的一个字符串。 代码: 代码: data = sock.readpartial(128) # Read at most 128 bytes
readpartial 方法,不能接受非阻塞的 flag,他有时会阻塞:IO 对象的 buffer 是空的;流的内容为空;流没有到达文件末尾
。 因此,如果流中还有数据的话,readpartial 将不会阻塞. 如果流没有数据,并且他已经抵达文件的末尾,readpartial 将会立即抛出一个 EOFError. 如果调用阻塞,他将会等待直到接收到数据或者得到一个 EOF. 当 sysread 调用在阻塞模式下,他的行为与 readpartial 相似. 6 操作路径名
先来看一下 File.dirname 和 File.basename 方法: 代码: 代码: str = "/home/dave/podbay.rb" dir = File.dirname(str) # "/home/dave" file1 = File.basename(str) # "podbay.rb" file2 = File.basename(str,".rb") # "podbay"
File.split 方法,可以将一个文件的路径名和文件名分隔开: 代码: 代码: info = File.split(str) # ["/home/dave","podbay.rb"]
类方
法 expand_path 将一个相对路径,转换为一个绝对路径名: 代码: 代码: Dir.chdir("/home/poole/personal/docs") abs = File.expand_path("../../misc") # "/home/poole/
misc"
对于打开的文件,path 将会返回这个文件的路径名: 代码: 代码: file = File.new("../../foobar") name = file.path # "../../foobar"
类方法类方法 join 正好和 split 相反:
代码: 代码: path = File.join("usr","local","bin","someprog")
7 使用 Pathname pathname 类实际上是,Dir, File, FileTest,和 FileUtils 的包装器,它包含他 们的很多功能: 代码: 代码: require 'pathname' path = Pathname.new("home/hal") file = Pathname.new("file.txt") p2 = path + file path.directory? # true path.file? # false p2.directory? # false p2.file? # true puts parts = p2.split puts ext = p2.extname # [Pathname:/home/hal, Pathname:file.txt] # .txt
再看看其他的有用的方法: 代码: 代码: p1 = Pathname.new("//") p1.root? p2 = Pathname.new("/home/poole") p3 = p2.parent items = p2.children # odd but legal # true # Pathname:/home # array of Pathnames (all files and # dirs immediately under poole)
relative 和 absolute 判断路径是否是相对的: 代码: 代码: p1 = Pathname.new("/home/dave") p1.absolute? p1.relative?
# true # false
8 Command-Level 文件操作 其实也就是 copy, delete, rename,等等 些操作了: 代码: 代码: File.delete("history") File.unlink("toast") File.rename("Ceylon","SriLanka") File.link("/etc/hosts","/etc/hostfile") # hard l