迅速掌握Ruby文件行數(shù)計算技巧
作者:佚名
Ruby文件行數(shù)計算對于一個初學者來說還是比較難以掌握的,在下面這篇文章中,我們將會學到一些關于Ruby文件行數(shù)計算的相關技巧。
對于Ruby的理解,我們需要不斷的從實際代碼編寫中去總結經(jīng)驗,提升我們對這項語言的理解程度。在這里我們就為大家介紹一種技巧,關于Ruby文件行數(shù)計算的相關技巧。#t#
代碼核心在于獲取某文件行數(shù) 以及 某文件夾下所有文件的遍歷,前者好像找不到什么好的API,我使用的是遍歷的方法。后者有很多重方法,就用簡單點的Find了,下次嘗試用Tree的形式并生成xml
PS 本來想弄個后綴過濾,后來發(fā)現(xiàn)linux下許多文件都沒有后綴的~~~不管了。
Ruby文件行數(shù)計算代碼示例:
- module Enumerable
- # function to get total lines for file
- def total_lines
- lines = 0
- each_with_index {|content,lines|}
- return lines+1
- end
- end
- class CheckLines
- require 'find'
- @check_type = %w{txt rb erb yml html css xml}
- def initialize(directory)
- @total_lines = 0
- if File.directory?(directory)
- @directorydirectory = directory
- @contents = {}
- self.go
- else puts "#{directory} is not a directory! check it out!" and return
- end
- end
- def go
- if @directory
- Find.find @directory do |path|
- pathpathlite = path.gsub(@directory,'')
- if File.file? path
- File.open path do |f|
- tmp_line = f.total_lines
- @contents.store(pathlite,tmp_line)
- @total_lines += tmp_line
- end
- end
- end
- puts @total_lines
- end
- end
- def details
- @contents.each do |key,value|
- puts "#{key} file has lines of #{value}"
- end
- end
- end
以上就是Ruby文件行數(shù)計算的使用技巧介紹。希望對大家有所幫助。
責任編輯:曹凱
來源:
javaeye.com