Locked lesson.
About this lesson
We'll learn to output the contents of a file into an array.
Exercise files
Download this lesson’s related exercise files.
Open a File into an Array - Solution.docx60.9 KB Open a File into an Array.docx
60.8 KB
Quick reference
Open a File into an Array
Once you open a file, you can do all sorts of things with it's content.
When to use
Use this whenver you want to stuff the contents of a file into an array.
Instructions
First, we need to create an empty array:
my_array = [ ]
Then you need to loop etc:
# Open the file
my_file = File.open("stuff.txt")
# Create an empty array
my_array = []
# Loop and push stuff into array
while ! my_file.eof?
stuff = my_file.gets.chomp
my_array << stuff
end
# Output the array to the screen
puts my_array
# Close the file
my_file.close
Hints & tips
- To create an empty array: my_array = [ ]
- To add items to an array: my_array << "Bob"
Lesson notes are only available for subscribers.