Recursive line counter (review?)

Hi

I’m practicing ruby everyday on small tools to learn more, could anyone
review what I’ve coded today ? This is a basic line of code counter
(pure ruby), any feedback welcome!

thanks !

Thibaut

def loc_file(file)
File.open(file).inject(0) { |loc,line| loc+1 }
end

def loc_by_extension(root,ext)
Dir[root+ext].inject(0) { |total,f| total + loc_file(f) }
end

[".cs",".cpp",".h",".resx"].each do |ext|
puts “#{loc_by_extension(‘c:/evolutionsyncfusion/**/’,ext)} loc for
#{ext}”
end

I like your use of inject. However, the code you show is not
recursive, but thats not really important unless it being recursive was
the point…

When I was playing with a similar bit of code I recall using

IO.readlines(‘filename’).size

I also recall trying

f=File.open(‘filename’)
f.seek(0,IO::SEEKEND)
lc = f.lineno

If speed is an issue oyu might want to compare various methods.

Happy coding

Cheers

ChrisH wrote:

I like your use of inject. However, the code you show is not
recursive, but thats not really important unless it being recursive
was the point…

When I was playing with a similar bit of code I recall using

IO.readlines(‘filename’).size

This doesn’t work well with large files and also uses more resources
(memory).

I also recall trying

f=File.open(‘filename’)
f.seek(0,IO::SEEKEND)
lc = f.lineno

Does this really work? I can’t believe it because during seeking the
file
is actually not read - so the IO instance cannot really count line
numbers, can it?

If speed is an issue oyu might want to compare various methods.

Yeah.

Kind regards

robert

Thibaut Barrère wrote:

def loc_file(file)
File.open(file).inject(0) { |loc,line| loc+1 }
end

You’re not properly closing IO’s. Rather do

def loc_file(file)
File.open(file) {|io| io.inject(0) { |loc,line| loc+1 } }
end

Kind regards

robert