Ruby文件行数计算对于一个初学者来说还是比较难以掌握的,在下面这篇文章中,我们将会学到一些关于Ruby文件行数计算的相关技巧。

对于Ruby的理解,我们需要不断的从实际代码编写中去总结经验,提升我们对这项语言的理解程度。在这里我们就为大家介绍一种技巧,关于Ruby文件行数计算的相关技巧。#t#

迅速掌握Ruby文件行数计算技巧  Ruby文件行数计算 第1张

代码核心在于获取某文件行数 以及 某文件夹下所有文件的遍历,前者好像找不到什么好的API,我使用的是遍历的方法。后者有很多重方法,就用简单点的Find了,下次尝试用Tree的形式并生成xml

PS 本来想弄个后缀过滤,后来发现linux下许多文件都没有后缀的~~~不管了。

Ruby文件行数计算代码示例:

  1. moduleEnumerable
  2. #functiontogettotallinesforfile
  3. deftotal_lines
  4. lines=0
  5. each_with_index{|content,lines|}
  6. returnlines+1
  7. end
  8. end
  9. classCheckLines
  10. require'find'
  11. @check_type=%w{txtrberbymlhtmlcssxml}
  12. definitialize(directory)
  13. @total_lines=0
  14. ifFile.directory?(directory)
  15. @directorydirectory=directory
  16. @contents={}
  17. self.go
  18. elseputs"#{directory}isnotadirectory!checkitout!"andreturn
  19. end
  20. end
  21. defgo
  22. if@directory
  23. Find.find@directorydo|path|
  24. pathpathlite=path.gsub(@directory,'')
  25. ifFile.file?path
  26. File.openpathdo|f|
  27. tmp_line=f.total_lines
  28. @contents.store(pathlite,tmp_line)
  29. @total_lines+=tmp_line
  30. end
  31. end
  32. end
  33. puts@total_lines
  34. end
  35. end
  36. defdetails
  37. @contents.eachdo|key,value|
  38. puts"#{key}filehaslinesof#{value}"
  39. end
  40. end
  41. end

以上就是Ruby文件行数计算的使用技巧介绍。希望对大家有所帮助。

转载请说明出处
知优网 » 迅速掌握Ruby文件行数计算技巧

发表评论

您需要后才能发表评论