Ruby - File File Name

Introduction

Windows and Unix-related operating systems have different ways of specifying filenames.

Windows filenames look like c:\directory\filename.ext, whereas Unix-style filenames look like /directory/filename.ext.

You can use File class join method to create path that would work on both systems.

On Windows, you can use File.join to put together a filename using directory names and a final filename:

File.join('full', 'path', 'here', 'filename.txt') 
#full\path\here\filename.txt 

On Unix-related operating systems, such as Linux, the code is the same:

File.join('full', 'path', 'here', 'filename.txt') 
#full/path/here/filename.txt 

File.join method allows you to write the same code to run on both systems.

The separator itself is stored in a constant called File::SEPARATOR.

You can turn a filename into an absolute filename by appending the directory separator to the start, like so:

File.join(File::SEPARATOR , 'full', 'path', 'here', 'filename.txt') 
#/full/path/here/filename.txt 

You can use File.expand_path to turn basic filenames into complete paths.

File.expand_path("main.rb") 
#/Users/peter/text.txt 

Related Topic