Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 ="test.txt")

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

puts loc
puts comments

I'm just looking for a review.

share|improve this question
up vote 3 down vote accepted

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]
    {comments: state[:comments] + 1, in_multiline_comment: !line.match(/\*\//)}
    case line 
    when /\/\*/
      {comments: state[:comments] + 1, in_multiline_comment: !line.match(/\*\//)}
    when /\/\//
      {comments: state[:comments] + 1}
      {lines: state[:lines] + (line.strip.empty? ? 0 : 1)}

Notice that you don't worry about stateful variables anymore, we just think "if I have this input and this current state, what output would I want?". Once you've covered all scenarios, the algorithm is done (hopefully leaving behind a declarative and maintainable code).

share|improve this answer
Thanks, definitively a whole different way of solving it. Plus a nice explanation of how it's done. – Agush Dec 21 '12 at 23:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.