Am 03.02.2013 02:13, schrieb Soichi Ishida:
> ruby 1.9.3p362 (2012-12-25 revision 38607) [x86_64-darwin12.2.1]
>
> I am trying to analyze a file and extract necessary data from it.
> First I need to count the total number of lines and the blank lines. the
> class and methods follow.

Since you are reading the complete file into memory anyway
(with File.read), you could get the information you need
much easier without any loop at all:

content = File.readlines('file.dat')
content.size
content.grep(/^\s*$/).size

> class DataExtractor
>      attr_reader :file_name
>      def initialize(file)
>          @file_name = file
>      end
>
>      def total_lines
>          @lines = 0
>          f = File.open(@file_name, 'r')
>          f.read.each_line do |l|
>              @lines += 1
>          end
>          f.close
>          @lines
>      end
>
>      def total_blank_lines
>          regEx = /^[\s]*$\n/
>          @total_blank_lines = 0
>          f = File.open(@file_name, 'r')
>          f.read.each_line do | line |
>              if line =~ regEx
>                  @total_blank_lines += 1
>              end
>          end
>          f.close
>          @total_blank_lines
>      end
>      ....
>
> The problem is that each method has 'File.open...each_line do ' so the
> whole loop gets executed separately.
>
> Don't you think this is inefficient?  Is there better ways to develop
> methods so that the loop is needed only once?
>
> soichi


-- 
<https://github.com/stomar/>