1

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!

thenengah
  • 42,557
  • 33
  • 113
  • 157

3 Answers3

2

http://www.ruby-doc.org/stdlib/libdoc/find/rdoc/classes/Find.html

Module that implements something like find.

The example on the page gives an example of getting size of all files in a directory. Should be pretty trivial to change it to count total lines.

I would recommend not doing this in ruby unless you had too...

wc -l `find /path/to/dir -type f` | tail -1
Stephen Garle
  • 299
  • 1
  • 5
1

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

Community
  • 1
  • 1
Ghoti
  • 2,388
  • 1
  • 18
  • 22
1

@Ghoti, I would add this as a comment for you, but do not have enough status.

Make use of File.file? and File::directory? will help in differentiating the two so that you will know if you need to burrow deeper into a directory or read a file.

scradge
  • 146
  • 5
  • Well, the burrowing's being done by that Dir[] statement, but you don't want to call the puts on a directory, and not on a binary file either. :D – Ghoti Jul 01 '11 at 12:49
  • It would be a pretty slick feature if you could puts a directory and it puts all the files in it ;-) – scradge Jul 01 '11 at 17:17