你会如何编写一个ruby脚本,例如get_lines.rb file_name.rb ,它返回一个应用程序中的代码总数/行,通过文件夹>文件夹> foler递归,例如app / modes,app / controllers等...全部文件!
How would you write a ruby script such as get_lines.rb file_name.rb where it returns the total number/lines of code in an application that is recursive through folder > folder > foler such as app/modes, app/controllers etc... all files!
最满意答案
通常我不会 - 我会使用shell实用程序。 认真。
另外,您想要包含评论吗? 等等
这里有一个很好的答案,不是在这里使用Ruby: 如何递归地计算目录中的所有代码行?
如果我正在接近这个以实际做的目的,我会这样做:
Dir['**/*.*'].each do |fname| puts "#{fname} #{linecount(fname)}" endLinecount就像是
def linecount(fname) File.open(fname, "r") do |f| return f.readlines.length end end顺便说一句,这是一个讨厌的黑客行为,因为它只是为了查看数组的长度而将整个文件读入内存,您可能希望获取每一行并在阅读时计算它们。
你只需要递增计数器就可以摆脱只有注释的空白或行。
就像是
lines = f.readlines lines.delete_if { |l| l =~ /^[[:space:]]*#|^$/ } return lines.length顺便说一句,我没有测试过regexp。
作为读者的练习 - 弄清楚'if'语句是什么,你需要在put结束时停止它对目录的抨击:D
Generally I wouldn't - I'd use a shell utility. Seriously.
Also, do you want to include comments? Etc. etc.
There's a very good answer to this, not using Ruby here: How to count all the lines of code in a directory recursively?
If I were approaching this with the intent of actually doing it I'd do this:
Dir['**/*.*'].each do |fname| puts "#{fname} #{linecount(fname)}" endLinecount would be something like
def linecount(fname) File.open(fname, "r") do |f| return f.readlines.length end endThis is a nasty hack by the way, because it reads the whole file into memory just to see how long the array is, you might want to get each line and count them as you read through.
You could get rid of blanks or lines that are only comments too by only incrementing the counter.
Something like
lines = f.readlines lines.delete_if { |l| l =~ /^[[:space:]]*#|^$/ } return lines.lengthI haven't tested that regexp by the way.
As an exercise for the reader - work out what the 'if' statement is you need to put on the end of the puts to stop it barfing on directories :D
更多推荐
发布评论