SoFunction
Updated on 2025-04-07

Summary of some commonly used file operation methods in Ruby

When you are a beginner, you need to learn a lot. Now you have to try to use Ruby to write a script, which uses a lot of file-related operations. Here we organize some of them in stages. Easy to search again later.

Whether the file or directory exists

Copy the codeThe code is as follows:

?('file_path')

Is it a file or not

Copy the codeThe code is as follows:

?("file_path")

Is it a directory?

Copy the codeThe code is as follows:

?("file_path")

Get file name from path

Copy the codeThe code is as follows:

('/tmp/')  #=> ""

#Remove extension from the above result

('/tmp/', '.log') #=> "adb"
#or
('/tmp/', '.*')   #=> "adb"


List all subfiles in the directory

Copy the codeThe code is as follows:

#Replace puts child for your own operation
Dir['/tmp/*'].each{|child|puts child}

Obtain the parent directory

Copy the codeThe code is as follows:

#The parent path of a specific directory
File.expand_path("..",specific_path)
#The parent path of the current directory
File.expand_path("..",)
#or
File.expand_path("..")