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.