Skip to Main Content
TWIL
Ruby
Image of Katie illustrating the process of file path assembly and existence verification in Ruby programming, highlighting the use of the File class for precise and secure file handling.

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
Katie Linero's profile picture
Katie Linero

Senior Software Engineer

Related Posts

Image for 'This Week I Learned' blog post featuring tips on managing Git branches including renaming and syncing with remote changes.
October 8, 2019 • Frank Valcarcel

TWIL 2019-10-04

Join us for ‘TWIL,’ where Emily shares innovative Git tips for managing branches with rewritten history. Learn to sync local branches with remote changes and rename them effectively.

Image for the "TWIL" blog series featuring an array of web development icons representing topics like Rails, React, Heroku, and iTerm.
October 17, 2019 • Frank Valcarcel

TWIL 2019-10-11

Discover quick yet insightful learnings this week on “TWIL.” Dive into web development with Rails HTML preprocessors, React’s useEffect, and more.