From: "Jesús Gabriel y Galán" Date: 2011-07-28T19:24:37+09:00 Subject: Re: Counting lines of code in a ruby code file ignoring method code lines in the process On Thu, Jul 28, 2011 at 12:15 PM, Harry Kakueki wrote: > On Wed, Jul 27, 2011 at 11:51 PM, Harry Truax wrote: >> Hello, >> >> I am re-posting this in case it did not make it when I posted it earlier: >> >> Hello, >> >> I am writing a Ruby program that reads a ruby code file and counts the >> number of lines of code that are in the file. I do not want to count >> the number of lines of code in any methods that may be in the file. I can >> look for a line of code that begins with 'def' and I know that the method >> will have an 'end' on the last line, but I am trying to figure out how to >> not get the 'end' confused with other 'end's that may be inside the method >> itself, like 'end's associated with if statements and case statements as an >> example. >> >> I was thinking that once I see a 'def' starting a code line I would know >> that I am reading in a method, so I would increment an 'end' counter >> by 1. I would also increment the end counter each time I read a 'case' or an >> 'if', or any other expression that required it's own 'end'. Each time I >> would read an 'end' I would decrement the 'end' counter, and when it equals >> zero, I would know that I read in the entire method, then I could start >> counting code lines again. >> >> Any ideas would be greatly appreciated. >> >> Thanks! >> > > But, I think it is not so simple. > How would you count the lines in this code? > 2 or 4? > There is 1 def. > There are 3 ifs. > There are 2 ends. > > > class Array >  def silly(num) >    result = "small" if self[num] < 100 >    result = "medium" if self[num] > 100 >    result = "large" if self[0] == 1 >    result >  end > end > > > arr = [1,2,3,4,5,6,7] > p arr.silly(3) As I understood from the requirements, that would be 2, since the rest of the code is inside class or def. So I thought about using ruby_parser, removing the toplevel sexps that were :class or :defn, but then I still don't know how to count the lines in the rest of them. Jesus.