Ruby File Handling Examples / Reference

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.

check if a file exists

if(File.exist?("filename"))
    #do stuff
end

open file

file = File.open("path-to-file", "r")

open file relative path

path_to_file = File.expand_path("relative-path-to-file", File.dirname(__FILE__))
file = open(path_to_file, "r")

read a file's contents to a string

contents = File.open("path-to-file","r").read    

Dialogue & Discussion