File Handling
This page was last reviewed on Sep 15, 2023.
Dot Net Perls
Files. In Ruby, we have methods like readline and readlines() that can incrementally process files. This is usually best for performance.
Ruby is not a low-level language, and file handling reflects this. Usually we do not even need a loop to read in a file in this language.
Open. This example opens a file with File.open. It reads in each line of the file. It uses an until-loop to sequentially access each line, until the end of the file (eof).
Start The file opened should be stored in the same directory as the program. The leading slash indicates this.
Tip Reading in files line-by-line is often more efficient for long files than reading them all at once. It uses less memory.
Here In this example, the data.readline() call returns the line read. It includes the trailing newline, if one exists.
Info When we use the print method, the trailing newline is printed to the output.
# Open data file with open. data = File.open("/data.txt") # Until end-of-file. until data.eof() # Read line. line = data.readline() # Print line. print line end
Line 1 Line 2 And line 3
Exists. A file that does not exist cannot be read. In clearer terms, we must first test a file for existence. In Ruby we use the "File.exists?" method for this.
Detail The "exists?" predicate method returns true or false. We can test it directly in an if-statement.
Here This program will likely print "No" on your system. If you place a "perls.txt" file in the root directory, it prints "Yes".
# See if this file exists. if File.exists?("/perls.txt") puts "Yes" else puts "No" end
Size. How can you get the size, in bytes, of a file? A simple approach is to use File.stat and access its size property. This returns the number of bytes in the file.
Info For this example, make sure to change the path to a file that exists. An exception is encountered if the file does not exist.
# Get size of this file. s = File.stat("/perls/p") bytes = s.size # Display the file size. puts bytes
Readlines. It is easy to place an entire text file into an array of lines. This allows us to loop over and process the array, avoiding further disk reads.
Here We invoke IO.readlines, which receives a file path argument. Often we can use relative paths.
Next We read a file called "file.txt" in my "C:\perls\" folder. For your system, please change the path to one that exists.
lines = IO.readlines("/perls/file.txt") # Display line count. puts lines.length # Loop over all lines in the array. lines.each do |line| puts line end
3 Line one Line two Line three
IO.foreach. This method iterates over the lines in a file. We pass it the file location. We can use IO.foreach in a do-loop with an iteration variable or with an iterator block.
Note The first two lines have only eight characters, but have lengths of 9. The ending whitespace character "\n" is being counted.
# Use IO.foreach with do. IO.foreach("/perls/file.txt") do |line| puts line end # Display lengths of lines with block. IO.foreach("/perls/file.txt") {|line| puts line.length}
Line one Line two Line three 9 9 10
Newlines. When we read lines from files, the trailing newlines are included. We must use a method like chomp() to clean up our strings.
Here We call "chomp!" on each string returned from readline. Many other string methods can be used.
data = File.open("/files/gems.txt") until data.eof() line = data.readline() # Chomp line to remove trailing newline. line.chomp! puts "[" << line << "]" end
[ruby] [sapphire] [diamond] [emerald] [topaz]
Comma-separated values. Split can be paired with an iterator like IO.foreach. In this way we can handle CSV files. An example is available for the split() method.
String split
Complete support. Ruby provides complete support for file handling. It accesses the file system with methods from the IO and File classes. IO is integrated into the language.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 15, 2023 (edit).
© 2007-2024 Sam Allen.