Re: Final iteration lost?
Robert Klemme <[email protected]> Sat, 10 Aug 2019 12:17:59 +0200
| Newsgroups | gmane.comp.lang.ruby.general |
|---|---|
| Message-ID | <CAM9pMnPwS7QcTeS1dt9bKQ3_PV0DC8Y_ftRN7n+1PPfvtiw7bg@mail.gmail.com> |
On Thu, Aug 8, 2019 at 1:07 PM Leam Hall <[email protected]> wrote: > I'm parsing a data file with each_line, each section starts with a line > that ends in ")". Each section has 2-3 subsections, delimited by blank > lines. The original test for a new section was: > > if line.end_with?(')') > > However, that means the last section is never dealt with, since the > "each_line" ends at EOF. What I currently have is a line to process the > data once the each_line block is finished. > > if data.count > 0 > jobs << Job.new(data) > end > > Full code below. > I will only focus on the line parsing. The pattern I use for this uses case is like this: require 'pp' def process_sections(sections) sections || return # whatever pp sections end sections = nil ARGF.each_line do |line| case line when /\($/ # beginning of section process_sections(sections) sections = [line] when /^$/ # new sub section sections and sections << "" else sections and sections.last << line end end process_sections(sections) I find case with regular expressions much easier to digest than if elsif cascades. And of course you need one final processing step after the loop to make sure you process outstanding data. Kind regards robert -- [guy, jim, charlie].each {|him| remember.him do |as, often| as.you_can - without end} http://blog.rubybestpractices.com/ Unsubscribe: <mailto:[email protected]?subject=unsubscribe> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>