本文簡要介紹ruby語言中 Pathname類
的用法。
Pathname
代表文件係統上文件或目錄的名稱,但不代表文件本身。
路徑名取決於操作係統:Unix、Windows 等。該庫適用於本地操作係統的路徑名,但實驗性支持非 Unix 路徑名。
Pathname
可以是相對的或絕對的。直到您嘗試引用該文件時,該文件是否存在才重要。
Pathname
是不可變的。它沒有破壞性更新的方法。
此類的目標是以比標準 Ruby 提供的更簡潔的方式操作文件路徑信息。下麵的示例演示了差異。
File
、 FileTest
的所有函數以及 Dir
和 FileUtils
的一些函數都包含在內,這並不奇怪。它本質上是所有這些的門麵,甚至更多。
例子
示例 1:使用 Pathname
require 'pathname'
pn = Pathname.new("/usr/bin/ruby")
size = pn.size # 27662
isdir = pn.directory? # false
dir = pn.dirname # Pathname:/usr/bin
base = pn.basename # Pathname:ruby
dir, base = pn.split # [Pathname:/usr/bin, Pathname:ruby]
data = pn.read
pn.open { |f| _ }
pn.each_line { |line| _ }
示例 2:使用標準 Ruby
pn = "/usr/bin/ruby"
size = File.size(pn) # 27662
isdir = File.directory?(pn) # false
dir = File.dirname(pn) # "/usr/bin"
base = File.basename(pn) # "ruby"
dir, base = File.split(pn) # ["/usr/bin", "ruby"]
data = File.read(pn)
File.open(pn) { |f| _ }
File.foreach(pn) { |line| _ }
示例 3:特殊函數
p1 = Pathname.new("/usr/lib") # Pathname:/usr/lib
p2 = p1 + "ruby/1.8" # Pathname:/usr/lib/ruby/1.8
p3 = p1.parent # Pathname:/usr
p4 = p2.relative_path_from(p3) # Pathname:lib/ruby/1.8
pwd = Pathname.pwd # Pathname:/home/gavin
pwd.absolute? # true
p5 = Pathname.new "." # Pathname:.
p5 = p5 + "music/../articles" # Pathname:music/../articles
p5.cleanpath # Pathname:articles
p5.realpath # Pathname:/home/gavin/articles
p5.children # [Pathname:/home/gavin/articles/linux, ...]
函數分解
核心方法
這些方法有效地操縱了 String
,因為這就是路徑。除了 mountpoint?
、 children
、 each_child
、 realdirpath
和 realpath
之外,這些都不能訪問文件係統。
-
+
File
狀態謂詞方法
這些方法是 FileTest 的外觀:
File
屬性和操作方法
這些方法是 File 的外觀:
-
chown
(owner, group) -
lchown
(owner, group) -
fnmatch
(模式,*args) -
fnmatch?
(模式,*args) -
open
(*args, █) -
utime
(atime, mtime)
目錄方法
這些方法是 Dir 的外觀:
-
each_entry
(&塊)
IO
這些方法是 IO 的門麵:
-
each_line
(*args, █)
實用程序
這些方法是 Find
、 FileUtils
和其他方法的混合:
Method
文檔
如上節所示, Pathname
中的大多數方法都是門麵。這些方法的文檔通常隻是說,例如,“請參閱 FileTest.writable?
”,因為無論如何您都應該熟悉原始方法,並且其文檔(例如通過 ri
)將包含更多信息。在某些情況下,將進行簡要說明。
相關用法
- Ruby Pathname.<=>用法及代碼示例
- Ruby Pathname.children用法及代碼示例
- Ruby Pathname.descend用法及代碼示例
- Ruby Pathname.getwd用法及代碼示例
- Ruby Pathname.ascend用法及代碼示例
- Ruby Pathname.pwd用法及代碼示例
- Ruby Pathname.+用法及代碼示例
- Ruby Pathname.sub_ext用法及代碼示例
- Ruby Pathname.glob用法及代碼示例
- Ruby Pathname.entries用法及代碼示例
- Ruby Pathname.join用法及代碼示例
- Ruby Pathname.sub用法及代碼示例
- Ruby Pathname.each_filename用法及代碼示例
- Ruby Pathname.absolute?用法及代碼示例
- Ruby Pathname.relative?用法及代碼示例
- Ruby Pathname.each_child用法及代碼示例
- Ruby Parser類用法及代碼示例
- Ruby Parser.use_markup用法及代碼示例
- Ruby PackageTask類用法及代碼示例
- Ruby PrettyPrint.current_group用法及代碼示例
- Ruby Process.groups用法及代碼示例
- Ruby Process.wait2用法及代碼示例
- Ruby Process.getpgrp用法及代碼示例
- Ruby Proc.eql?用法及代碼示例
- Ruby PTY.open用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Pathname類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。