ruby can be used to read files. You can either read a file directly into a string variable or read a file line by line.
These functionality ruby provides out of the box is for read files on the hard disk, not on the cloud.
Related Course: Learn Ruby On Rails For Web Development
The ruby program below reads a file from the disk. ruby will read the file from the same directory as your program. If the file is in another directory, specify its path.
If you want to read a file at once, you can use:
content = File.read("read.rb")
This reads the entire file into a ruby string.
If you want to read a file line by line, into an array, you can use this code:
lines = File.readlines('read2.rb')
# It's an array so we can access elements
- Think of when you’d read a file ‘line by line’ vs ‘at once’?
- Create a new file containing names and read it into an array