Locked lesson.
About this lesson
How to open another file in your Ruby file.
Quick reference
Opening a File
Opening a file with Ruby is super easy!
When to use
Use this any time you have an external file that you need to access.
Instructions
To open a file in Ruby, use the File class and .new method:
my_file = File.new("filename.txt")
When you open a file, you need to close it when you're done.
my_file.close
To pull stuff out of your file line by line:
while ! my_file.eof?
stuff = my_file.gets.chomp
puts stuff
end
Hints & tips
- my_file = File.new("filename.txt")
- my_file.close
Lesson notes are only available for subscribers.