A summary of some common file operations in Ruby and a summary of ruby operations
A lot of Ruby beginners need to learn. Now we are trying to use Ruby to write a script. Many file-related operations are used, which are sorted in stages here. This facilitates subsequent searches.
Whether the file or directory exists
Copy codeThe Code is as follows:
File. exist? ('File _ path ')
Is it a file?
Copy codeThe Code is as follows:
File. file? ("File_path ")
Is it a directory?
Copy codeThe Code is as follows:
File. directory? ("File_path ")
Get file name from path
Copy codeThe Code is as follows:
File. basename ('/tmp/adb. log') # => "adb. log"
# Remove the extension from the preceding result
File. basename ('/tmp/adb. log','. log') # => "adb"
# Or
File. basename ('/tmp/adb. log','. * ') # => "adb"
List all sub-files in a directory
Copy codeThe Code is as follows:
# Replace puts child with your own operations
Dir ['/tmp/*']. each {| child | puts child}
Obtain parent directory
Copy codeThe Code is as follows:
# Parent path of a specific directory
File. expand_path ("...", specific_path)
# Parent path of the current directory
File. expand_path ("...", Dir. pwd)
# Or
File. expand_path ("..")