From: "Jesús Gabriel y Galán" Date: 2010-07-30T16:33:12+09:00 Subject: Re: my script just read one line? On Fri, Jul 30, 2010 at 1:58 AM, Junhui Liao wrote: > Dear Jesús Gabriel y Galán and all, > >> File.open("../original_data/test_2lines.tsv").each_line do |record| >>   a = record.chomp.split("\t") >>   a.each_slice(2).with_index do |(time,signal), index| >>     File.open("#{index}_debug_split"+".tsv" , "w") do |f| >>       f << "#{time}\t#{signal}\n" >>     end >>   end >> end > > This code ran well at 1.9.1 version of ruby. Since I tried at our > server where ruby is this version. BTW, I'm using 1.8.7. And also, File.open().each_line doesn't properly close the file, so we should be using File.foreach() > > Actually, I need to do this also: make the first line's time value > subtracted by other lines' corresponding time ones. > > First line: time_1.1, signal_1.1, time_1.2, signal_1.2... time_1.4096, > signal_1.4096. > Second line: time_2.1, signal_2.1, time_2.2, signal_2.2... time_2.4096, > signal_2.4096. > ....... > > I would like to do,  time_2.1 = time_2.1 - time_1.1 , time_2.2 = > time_2.2 - time_1.2 , > ...... time_2.4096 = time_2.4096 - time_1.4096. >                             ...... > Similar to other lines' time value. > > I tried to use a counter to pick up the first line (stupid way, I know) > than save in an array, and > take other lines time values to subtract this array, but failed. Since > it seemed > to the enumerator I could not access individual ? But "puts a[index] " > printed two items > (time and signal) well.  However, i could not print just time or signal > value. What I'd do is create an array for the first line with the times, and use that after on to substract. I've refactored a little bit to simplify (this is completely untested): File.open("../original_data/test_2lines.tsv") do |file| first_line = file.readline first_line_times = first_line.chomp.split("\t").each_slice(2).map {|time,signal| time} write_line_to_file first_line file.each_line do |record| line_data = record.chomp.split("\t") write_line_to_file line_data, first_line_times end end def write_line_to_file line, base_time = Hash.new(0) line_data.each_slice(2).with_index do |(time,signal), index| File.open("#{index}_debug_split"+".tsv" , "w") do |f| f << "#{time.to_i - base_time[index]}\t#{signal}\n" end end end Hope this gives you an idea to explore, Jesus.