Ruby File Methods
Ever wonder how ruby programm move to different directories and load different files and make sure
that the directories a certiain file is in to load.
Let’s begin by making sure we all understand the basics. In the Ruby programming language, it is common for gems or applications to use a combination of various methods discussed below to load the appropriate files.
FILE
Ruby has a constant called __FILE__
that contains a string.
This string contains the name of the current source file.
It give you a string representation of the path to the current file from where it was called.
for example, if we have a file test_file.rb
which looks like below:
# test_file.rb
# Output depends on the location and execution method of the script
puts __FILE__
and once we run it, we will get
$ ruby test_file.rb
# => test_file.rb
And now if we move the test_file.rb
script under ruby_src
folder
mkdir ruby_src
mv test_file.rb ./ruby_src/
now ruby script is in ruby_src/test_file.rb
path
and if we run it
$ ruby ruby_src/test_file.rb
# => ruby_src/test_file.rb
File.expand_path
File.expand_path
converts a pathname to an absolute pathname.
It’s commonly used to obtain the absolute path of a file or directory relative to the current working directory or another base directory.
example
puts File.expand_path('test_file.rb')
# => "/Users/rv/wrksp/test_file.rb"
File.join
File.join
is a method in Ruby’s File class used to construct a file path by joining one or more components together, ensuring proper handling of directory separators.
example
path = File.join('path', 'to', 'directory', 'rak.txt')
puts path
# => "path/to/directory/rak.txt"
File.dirname
Returns all components of the filename given in file_name except the last one.
File.dirname
is a handy method for extracting the directory component from a file path in Ruby, useful for various file and directory manipulation tasks in your Ruby programs.
File.dirname
works with both relative and absolute file paths.
It’s important to note that File.dirname
does not check whether the directory actually exists on the filesystem. It simply manipulates the provided path string.
example
file_path = "/path/to/directory/rak.txt"
directory = File.dirname(file_path)
puts directory
# => "/path/to/directory"
file_path2 = "path/to/directory2/"
directory2 = File.dirname(file_path2)
puts directory2
# => "/path/to/directory2"