# Count comments and lines of code

I wrote a small script as an answer for a Stack Overflow question, which referred to counting lines of code and comments (in C and C++ style).

f = File.open("test.txt")

loc = 0
while line = f.gets
if commented ||= line.match(/^\/\*/)
commented = nil if line.match(/\*\/\$/)
elsif line.match(/^\s*\/\//)
else
loc +=1 unless line.match(/^\s*\n/)
end
end

puts loc


I'm just looking for a review.

-

Your code looks pretty good to me, only that it's very imperative. I know it's not for everybody's taste, but a functional approach on text processing is also feasible.

My take: you start by defining an object (which may be a hash) to store the state (needed for in intermediate iterations and the final result), and then fold (reduce/inject) over the input lines, returning the next state on each step.

There are some edge cases (lines with multiple or nested comment) which I won't consider, let's keep it simple. I'd write:

initial_state = {lines: 0, comments: 0, in_multiline_comment: false}
final_state = open("test.txt").lines.inject(initial_state) do |state, line|
state_update = if state[:in_multiline_comment]
else
case line
when /\/\*/
when /\/\//