From: Soichi Ishida Date: 2013-02-03T10:13:00+09:00 Subject: Class for data analysis: File.open once 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. 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 -- Posted via http://www.ruby-forum.com/.