In Ruby, the followingCodeYou can obtain the absolute path of the current script:
Require 'pathname' puts pathname. New (_ file _). realpath
Save the above Code in test1.rb and put it in the root directory of drive D. During the test, we enter drive C and execute Ruby D:/test1.rb. The console will output the absolute path of the current Script: D:/test1.rb.
Someone may ask, is it possible to obtain dir. pwd? Actually, it is not feasible. Dir. pwd obtains the working directory. The working directory that I understand is the Ruby call directory. That is to say, the directory in which you get the called script, rather than the directory in which the script is located. We can do the following experiment, first create a test2.rb file, and enter the Code as follows:
Puts dir. pwd
After saving the file, we will also put the file under the root directory of drive D, and then go to drive C under the CMD command line (Note: Drive C !), Then execute Ruby test2.rb. What do you think it will output? D? Error: C :/! Let's see more clearly. Go to the C:/Windows/system directory under the CMD command line and execute Ruby D:/test2.rb. You will see that the output result is C: /Windows/system. This is clear. The directory in which you call the script and which directory is returned by Dir. pwd, but the actual path of the script is irrelevant. The official API writes a back-to-work Directory, which is easily understood as an absolute path.
Other operations include:
1. Get the file name of the current execution file:
_ File __
2. Obtain the directory of the current file
File. dirname (_ file __)
3. Obtain the complete path of the current execution File
Require 'pathname'
Pathname. New (_ file _). realpath
4. Obtain the complete directory path of the current execution File
Require 'pathname' pathname. New (file. dirname (_ file _). realpath
5. Source: http://www.leesoft.com.cn/2008/04/15/ruby%e8%8e%b7%e5%8f%96%e5%bd%93%e5%89%8d%e7%9a%84%e6%89%a7%e8%a1%8c%e6%96%87%e4%bb%b6%e7%9a%84%e8%b7%af%e5%be%84%e5%92%8c%e7%9b% AE %e5%bd%95/#comment-9