Use File.join to construct dynamic file paths

I commonly find myself having to build file paths by combining a constant (PROJECT_DIR), some known relative hardcoded path element (“../../data”), and/or some totally dynamic element (@user.name).

Ruby offers a bunch of basic string concatenation approaches for achieving this:

file_path = PROJECT_DIR + "../../data/" + @user.name

file_path = "#{PROJECT_DIR}../../data/#{@user.name}"

file_path = PROJECT_DIR << "../../data/" << @user.name

Instead, though, use File.join to construct the file path:

file_path = File.join(PROJECT_DIR, "../../data", @user.name)

I like this approach primarily because it removes any headaches associated with multiple or missing file path separators (slash/backslash).

Posted in ruby. Tags: . Leave a Comment »

Leave a Reply