The WC method is defined in Ruby to count the number of words and the number of lines

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:


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?}
       #In this example, the split method is used to split the word. When there are blank characters at the beginning of the line, the split method
       A blank string will be generated in the execution result, so we will delete the blank string.
       nline + = 1
       nword + = words.length
       nchar + = line.length
     end
   end
   puts "Number of lines in file: # {nline} \ nNumber of words in file: # {nword} \ nNumber of characters in file: # {nchar}"
end
wc ("sayGoodnight.rb")
# sayGoodnight.rb Here is just an example of the filename file. The files that follow can be changed. 


This article is from the "Fuqin Wine" blog, please make sure to keep this source http://yuhongchun.blog.51cto.com/1604432/1599344



The WC method is defined in Ruby to count the number of words and the number of lines


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.