Implementation of statistics file lines, words and characters in Ruby _ruby topics

Source: Internet
Author: User

In Ruby we define a WC method that is used to count the number of lines of text, words, and characters that appear in a file, and the Ruby Code program is as follows:

Copy Code code 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| w.empty?}
#本例中使用了split方法分割单词, when a white-space character is available at the beginning of the line, a blank string is generated in the execution result of the split method, so we
#会删除该空白字符串.
nline + 1
Nword + + Words.length
NCHAR + + Line.length
End
End
Puts "The number of lines of the file is: #{nline}\n file number of words: #{nword}\n file number of characters: #{nchar}"
End
WC ("saygoodnight.rb")
#sayGoodnight. RB here is just the filename file example, followed by the file 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.