count = 0
file.each_line do |ln|
# Manage multiline and single line comments.
# Exclude single line if and only if there isn't code on that line
next if ln =~ %r{^\s*(//|/\*[^*]*\*/$|$)} or (ln =~ %r{/\*} .. ln =~ %r{\*/})
count += 1
end
複数行のコメントだけでなくコードもある行にのみ問題があります。たとえば、次のようになります。
someCall(); /* Start comment
this a comment
even this
*/ thisShouldBeCounted();
でも:
imCounted(); // Comment
meToo(); /* comment */
/* comment */ yesImCounted();
// i'm not
/* Nor
we
are
*/
編集
次のバージョンはもう少し面倒ですが、すべてのケースを正しく数えます。
count = 0
comment_start = false
file.each_line do |ln|
# Manage multiline and single line comments.
# Exclude single line if and only if there isn't code on that line
next if ln =~ %r{^\s*(//|/\*[^*]*\*/$|$)} or (ln =~ %r{^\s*/\*} .. ln =~ %r{\*/}) or (comment_start and not ln.include? '*/')
count += 1 unless comment_start and ln =~ %r{\*/\s*$}
comment_start = ln.include? '/*'
end