用于检查应用程序中有多少行代码的Ruby脚本(Ruby script to check how many lines of code are in an application)

编程入门 行业动态 更新时间:2024-10-19 06:23:29
用于检查应用程序中有多少行代码的Ruby脚本(Ruby script to check how many lines of code are in an application)

你会如何编写一个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)}" end

Linecount就像是

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)}" end

Linecount would be something like

def linecount(fname) File.open(fname, "r") do |f| return f.readlines.length end end

This 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.length

I 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

更多推荐

本文发布于:2023-04-28 02:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329762.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中有   应用程序   脚本   代码   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!