Ruby File Handling Examples / Reference

Ruby File Handling Examples / Reference

Last updated:
Table of Contents

Check if file exists

if(File.exist?("absolute-path-to-file"))
  #do stuff
end

Open file

file = File.open("absolute-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 file contents to string

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