File Paths in Ruby

Here’s the translation of the Go code example to Ruby, formatted in Markdown suitable for Hugo:

The File::Separator constant and File.join method in Ruby provide functionality to work with file paths in a way that is portable between operating systems; dir/file on Linux vs. dir\file on Windows, for example.

require 'fileutils'

# File.join should be used to construct paths in a
# portable way. It takes any number of arguments
# and constructs a hierarchical path from them.
p = File.join("dir1", "dir2", "filename")
puts "p: #{p}"

# You should always use File.join instead of
# concatenating '/'s or '\'s manually. In addition
# to providing portability, File.join will also
# normalize paths by removing superfluous separators
# and directory changes.
puts File.join("dir1//", "filename")
puts File.join("dir1/../dir1", "filename")

# File.dirname and File.basename can be used to split a path to the
# directory and the file. Alternatively, File.split will
# return both in the same call.
puts "Dir(p): #{File.dirname(p)}"
puts "Base(p): #{File.basename(p)}"

# We can check whether a path is absolute.
puts File.absolute_path?("dir/file")
puts File.absolute_path?("/dir/file")

filename = "config.json"

# Some file names have extensions following a dot. We
# can split the extension out of such names with File.extname.
ext = File.extname(filename)
puts ext

# To find the file's name with the extension removed,
# use File.basename with a second argument.
puts File.basename(filename, ext)

# File.relative_path_from finds a relative path between a base and a
# target. It returns the relative path as a Pathname object.
rel = Pathname.new("a/b/t/file").relative_path_from("a/b")
puts rel

rel = Pathname.new("a/c/t/file").relative_path_from("a/b")
puts rel

To run the program:

$ ruby file_paths.rb
p: dir1/dir2/filename
dir1/filename
dir1/filename
Dir(p): dir1/dir2
Base(p): filename
false
true
.json
config
t/file
../c/t/file

In this Ruby version:

  1. We use File.join instead of filepath.Join to construct paths.
  2. File.dirname and File.basename are used instead of filepath.Dir and filepath.Base.
  3. File.absolute_path? is used to check if a path is absolute.
  4. File.extname is used to get the file extension.
  5. File.basename(filename, ext) is used to get the filename without the extension.
  6. Pathname#relative_path_from is used to find the relative path between two paths.

Note that Ruby’s path handling is generally more straightforward and doesn’t require a separate package like Go’s filepath. Most of the functionality is available directly in the File and Pathname classes.