Skip to content

Instantly share code, notes, and snippets.

@ryangreenberg
Created May 27, 2012 22:08
Show Gist options
  • Save ryangreenberg/2816092 to your computer and use it in GitHub Desktop.
Save ryangreenberg/2816092 to your computer and use it in GitHub Desktop.
How to read a file in Ruby
# How to read a file in Ruby
file_name = "example.txt"
# It's simple.
# Open the file in read mode ("r"), read it, and close it.
f = File.open(file_name, "r")
f.read
f.close
# Though "r" is the default mode, so you can remove that.
f = File.open(file_name)
f.read
f.close
# And actually, open is a method on Kernel, so you don't need File.
f = open(file_name)
f.read
f.close
# If you provide a block, the file will be automatically closed after
# yielding to the block
open(file_name) {|f| f.read }
# Then again, if you just need to read the file and you're not worried about
# the size of the file, you don't need to call open
File.read(file_name)
# Whatever you do, don't do this:
open(file_name).read
# because now you've forgotten to close the file, and you don't have any
# reference you could use to close it. This may be a problem if your program
# is going to be running for awhile.
# But what's in the file? YAML? You're not doing YAML.load(File.read(file_name))
# are you? Just use
YAML.load_file(file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment