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