Gavin Sinclair <gsinclair / soyabean.com.au> wrote:
> On Friday, January 31, 2003, 4:02:44 AM, Martin wrote:
> 
>> ts <decoux / moulon.inra.fr> wrote:
>>>>>>>> "M" == Martin DeMello <martindemello / yahoo.com> writes:
>>> 
>>> M>   flag = true if line =~ /^--begin--$/
>>> 
>>> 
>>>     next if 1 .. line =~ /^--begin--$/
>>> 
>>> it will begin the processing *after* the line /^--begin--$/
> 
>> Thanks! The line after --begin-- is precisely what I need.
> 
> This looks like confusing code.  Care to put it in context and give us
> a 3 minute tutorial?

Sure. Say you have a file that is divided into sections, demarcated by
section breaks. Here's an example:
  $ cat testfile
  precomments
  --begin--
  data
  --section--
  more data
  --section--
  still more data
  --end--
  postcomments

Now, when reading in the file via IO.foreach, we want to skip the
precomments, and start reading at --begin--. From the Pickaxe book:

  You can use a Ruby range as a boolean expression. A range such as
  exp1..exp2 will evaluate as false until exp1 becomes true. The range
  will then evaluate as true until exp2 becomes true. Once this happens,
  the range resets, ready to fire again.

So, to construct a range that is true whe the file starts, we use 
($. == 1) [where $. is the file counter], and have it return true until
we reach our begin statement. Here's the code for reading the above
file:

$ cat test.rb
i = 0
IO.foreach('testfile') {|line|
  next if ($. == 1)..(line =~ /^--begin--$/)
  case line
  when /^--section--$/
    i+=1; next
  when /^--end--$/
    break
  end
  puts "section #{i}: #{line}"
}

$ ruby test.rb
section 0: data
section 1: more data
section 2: still more data

martin