C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Path: 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.
Print: When we use the print method, the trailing newline is printed to the output.
Contents of data.txt
Line 1
Line 2
And line 3
Ruby program that uses File.open
# 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
Output
Line 1
Line 2
And line 3
True, false: 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 "Codex.txt" file in the root directory, it prints "Yes".
Ruby program that uses File.exists
# See if this file exists.
if File.exists?("/Codex.txt")
puts "Yes"
else
puts "No"
end
Output
Yes
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.
Ruby program that gets file size
# Get size of this file.
s = File.stat("/Codex/p")
bytes = s.size
# Display the file size.
puts bytes
Output
106252
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:\Codex\" folder. For your system, please change the path to one that exists.
Ruby program that uses readlines
lines = IO.readlines("/Codex/file.txt")
# Display line count.
puts lines.length
# Loop over all lines in the array.
lines.each do |line|
puts line
end
Output
3
Line one
Line two
Line three
Note: The first two lines have only eight characters, but have lengths of 9. The ending whitespace character "\n" is being counted.
Ruby program that uses IO.foreach
# Use IO.foreach with do.
IO.foreach("/Codex/file.txt") do |line|
puts line
end
# Display lengths of lines with block.
IO.foreach("/Codex/file.txt") {|line| puts line.length}
Output
Line one
Line two
Line three
9
9
10
Here: We call "chomp!" on each string returned from readline. Many other string methods can be used.
String, ChompFile contents: gems.txt
ruby
sapphire
diamond
emerald
topaz
Ruby program that uses chomp, readline
data = File.open("/files/gems.txt")
until data.eof()
line = data.readline()
# Chomp line to remove trailing newline.
line.chomp!
puts "[" << line << "]"
end
Output
[ruby]
[sapphire]
[diamond]
[emerald]
[topaz]