Directories in Ruby

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

Ruby provides several useful methods for working with directories in the file system.

require 'fileutils'

# Helper function to check for errors
def check(result)
  raise result if result.is_a?(Exception)
end

# Create a new sub-directory in the current working directory
check(Dir.mkdir('subdir', 0755))

# When creating temporary directories, it's good practice to ensure
# their removal. FileUtils.rm_rf will delete a whole directory tree
# (similarly to `rm -rf`).
at_exit { FileUtils.rm_rf('subdir') }

# Helper function to create a new empty file
def create_empty_file(name)
  File.write(name, '')
end

create_empty_file('subdir/file1')

# We can create a hierarchy of directories, including parents with
# FileUtils.mkdir_p. This is similar to the command-line `mkdir -p`.
check(FileUtils.mkdir_p('subdir/parent/child'))

create_empty_file('subdir/parent/file2')
create_empty_file('subdir/parent/file3')
create_empty_file('subdir/parent/child/file4')

# Dir.entries lists directory contents, returning an array of file names
entries = Dir.entries('subdir/parent')

puts "Listing subdir/parent"
entries.each do |entry|
  puts " #{entry} #{File.directory?("subdir/parent/#{entry}")}"
end

# Dir.chdir lets us change the current working directory, similarly to `cd`
Dir.chdir('subdir/parent/child')

# Now we'll see the contents of `subdir/parent/child` when listing the current directory
entries = Dir.entries('.')

puts "Listing subdir/parent/child"
entries.each do |entry|
  puts " #{entry} #{File.directory?(entry)}"
end

# Change back to where we started
Dir.chdir('../../..')

# We can also visit a directory recursively, including all its sub-directories
# Find.find accepts a starting point and yields each file or directory found
puts "Visiting subdir"
require 'find'
Find.find('subdir') do |path|
  puts " #{path} #{File.directory?(path)}"
end

To run the program:

$ ruby directories.rb
Listing subdir/parent
 . true
 .. true
 child true
 file2 false
 file3 false
Listing subdir/parent/child
 . true
 .. true
 file4 false
Visiting subdir
 subdir true
 subdir/file1 false
 subdir/parent true
 subdir/parent/child true
 subdir/parent/child/file4 false
 subdir/parent/file2 false
 subdir/parent/file3 false

This Ruby script demonstrates various operations on directories:

  1. Creating directories with Dir.mkdir and FileUtils.mkdir_p.
  2. Creating empty files.
  3. Listing directory contents with Dir.entries.
  4. Changing the current working directory with Dir.chdir.
  5. Recursively walking a directory tree with Find.find.

The script also uses at_exit to ensure cleanup of the created directories, similar to Go’s defer statement.

Ruby’s standard library provides rich functionality for file and directory operations, making it easy to work with the file system in a cross-platform manner.