A summary of some common file operations in Ruby and a summary of ruby operations

Source: Internet
Author: User

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 ("..")

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.