๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Paths and Directories

A path is the address of a file or a folder. This lesson builds paths from parts and looks inside folders.

Build and split a path

File.join links parts into one path. File.basename and File.extname then split the path back into pieces.

path = File.join "data", "reports", "notes.txt"
puts path
puts File.basename path
puts File.extname path

Make and use a folder

Dir.mkdir makes a folder on disk. A path built with File.join then stores a file inside that folder.

Dir.mkdir "data"
path = File.join "data", "notes.txt"
File.write path, "Stored inside"
text = File.read path
puts text
found = Dir.exist? "data"
puts found

List a folder sorted

Dir.children lists every name inside a folder. The sort call puts the names in a steady order for printing.

Dir.mkdir "fruit"
File.write "fruit/pear.txt", "P"
File.write "fruit/apple.txt", "A"
names = Dir.children "fruit"
p names.sort

Example

Dir.mkdir "shop"
File.write "shop/pear.txt", "P"
File.write "shop/apple.txt", "A"
names = Dir.children "shop"
p names.sort
here = Dir.children "."
p here.sort

Key points

  • File.join builds a path from separate parts.
  • File.basename gives the last part of a path.
  • File.extname gives the ending of a file name.
  • Dir.mkdir makes a new folder.
  • Dir.children lists the names inside a folder.

In this example, the program makes a folder and stores two small files inside it. Dir.children lists the names in the new folder in sorted order. The last listing shows the current folder, and main.rb sits there beside the new folder.

Note

Sort a listing before printing it, because the raw order can change.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which call lists the names inside a folder?