Forum: Ruby Recursive line counter (review?)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Thibaut Barrère (Guest)
on 2006-03-13 16:36
(Received via mailing list)
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
ChrisH (Guest)
on 2006-03-13 17:55
(Received via mailing list)
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
Robert K. (Guest)
on 2006-03-13 18:42
(Received via mailing list)
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
> <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
Robert K. (Guest)
on 2006-03-13 18:42
(Received via mailing list)
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
This topic is locked and can not be replied to.