Welcome to this week's TWIL, your go-to series for sparking micro-learning moments. Today, Katie offers insight into the world of programming with Ruby, specifically dissecting file path assembly and existence verification. Learn about in-depth file handling with Ruby by exploring how to use the File class, cautioning that strings created with File.join()
may not correspond to actual files and emphasize the importance of validating file paths using File.exist?
.
Ruby File Class
Ruby's built-in File
class provides a helpful interface for interacting with the filesystem, but there are also a few things to look out for.
File.join()
can be used to assemble a path from an arbitrary number of strings (or an array of strings), but the return value is simply a string and not a validated file path:
file = File.join('garbage_dir', 'garbage_file.xyz')
# file == 'garbage_dir/garbage_file.xyz'
With this in mind, if you need to check if a file exists, you should use File.exist?(file)
rather than just checking if file
, since if file
will return true
if file
has a value defined, regardless of whether the file actually exists.
file = File.join('garbage_dir', 'garbage_file.xyz')
# here, `if file` will be true (`file` is the string 'garbage_dir/garbage_file.xyz'),
# so `File.read` will raise an exception trying to open a file that doesn't exist
contents = File.read(file) if file
# here, `File.read` will not be executed because `if File.exist?(file)` will be false
contents = File.read(file) if File.exist?(file)
- Ruby