我有一個方法在Dir.chdir(File.dirname(__FILE__))里面使用。我正在使用它,以便我可以從任何地方運行 ruby?? 檔案而不會出現此錯誤:No such file or directory @ rb_sysopen - 'filename' (Errno::ENOENT).
第一次使用該方法可以正常作業,但第二次使用它會引發錯誤。請參閱下面的方法和確切錯誤。
def meth(string)
Dir.chdir(File.dirname(__FILE__))
hash = JSON.parse(File.read("file.json"))
# do something with hash and string
# return some value
end
meth("first string") # this returns what is expected
meth("second string") # this second usage of the method throws the error
錯誤示例指出我使用的行Dir.chdir(File.dirname(__FILE__)):
dir/decoder.rb:44:in `chdir': 沒有這樣的檔案或目錄@dir_s_chdir - lib (Errno::ENOENT)
不確定作業系統是否在這里起作用,我在 11.2.3 版上使用 m1 BigSur。
- 為什么會這樣?
- 需要做什么才能盡可能多地使用該方法而不會遇到錯誤?
uj5u.com熱心網友回復:
您在這里的問題似乎__FILE__是一個相對路徑,dir/decoder.rb并且該路徑在第一次Dir.chdir使用后變得無效,因為該命令更改了整個 Ruby 行程的作業目錄。我認為解決方案是在你的decoder.rb檔案中做這樣的事情:
DecoderDir = File.realpath(File.dirname(__FILE__))
def meth
Dir.chdir(DecoderDir)
# ...
end
我猜測 Ruby 解釋器第一次處理檔案時,時間足夠早,相對路徑__FILE__仍然指向正確的位置。所以,在那個時候,我們生成了一個絕對路徑以備將來使用。
順便說一句,行為良好的庫不應該運行,Dir.chdir因為它會影響整個 Ruby 行程中所有相對路徑的使用。我幾乎只運行Dir.chdir一次,并且在我的頂級腳本的開頭附近運行它。如果你正在制作一個可重用的庫,你可能想要做這樣的事情來計算你想要打開的檔案的絕對路徑:
DecoderJson = File.join(DecoderDir, 'file.json')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/392167.html
