Ruby traverses the contents of the file, the basic idea is to read row by line printing, is also a more common method:
#!/usr/bin/env ruby#encoding:utf8file = File.Open ("/tmp/abc.txt") file.each_line do |line| Print Lineendfile.close
Another way of writing, one-time read-once printing, relatively expensive memory, small file situations faster than the above method. Operating large files is not recommended.
#!/usr/bin/env ruby# encoding:utf8wholefile = File.read ("/tmp/abc.txt") print Wholefile
Summary
1. The first method compares flow editors like Sed,awk, and the second method is as violent as cat.
2. File.read does not need to explicitly close the file handle.
Extended
Before opening a file, determine if the file exists
#!/usr/bin/env ruby# encoding:utf8if file.exist? ("/tmp/abc.txt") file = File.Open ("/tmp/abc.txt") file.each_line do |line| Print line end File.closeelse puts "error:file not exist" end
Read-by-line, the file name as a parameter to the Ruby script
#!/usr/bin/env ruby# encoding:utf8filename = argv[0]if file.exist? (filename) file = File.Open (filename) file.each_line do |line| Print line end File.closeelse puts "error:file not exist" end
This article from the "Focus on Linux operation and Maintenance" blog, reproduced please contact the author!
Ruby traverses a file by line