Recursive line counter (review?)

T

Thibaut Barrère

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
 
C

ChrisH

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
<code>
IO.readlines('filename').size
</code>

I also recall trying
<code>
f=File.open('filename')
f.seek(0,IO::SEEKEND)
lc = f.lineno
</code>

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

Happy coding

Cheers
 
R

Robert Klemme

Thibaut said:
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

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
 
R

Robert Klemme

ChrisH said:
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
<code>
IO.readlines('filename').size
</code>

This doesn't work well with large files and also uses more resources
(memory).
I also recall trying
<code>
f=File.open('filename')
f.seek(0,IO::SEEKEND)
lc = f.lineno
</code>

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top