Statistics on the number of file lines, number of words, and number of characters in Ruby, and number of ruby lines

Source: Internet
Author: User

Statistics on the number of file lines, number of words, and number of characters in Ruby, and number of ruby lines

In Ruby, we define a wc method to count the number of lines, words, and characters in the file. The ruby code program is as follows:
Copy codeThe Code is as follows:
Def wc (filename)
Nline = nword = nchar = 0
File. open (filename) do | io |
Io. each_line do | line |
Words = line. split (/\ s +/). reject {| w. empty? }
# In this example, the split method is used to separate words. When there is a blank character at the beginning of the line, the execution result of the split method produces a blank string. Therefore
# This blank string is deleted.
Nline + = 1
Nword + = words. length
Nchar + = line. length
End
End
Puts "the number of lines of the file is: # {nline} \ n the number of words in the file is: # {nword} \ n the number of characters in the file is: # {nchar }"
End
Wc ("sayGoodnight. rb ")
# SayGoodnight. rb is only an example of the filename file. The file that is followed can be changed.

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.