Ruby traverses a file by line

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.