On 5/3/06, Rob Burrowes <rob / cs.auckland.ac.nz> wrote:
> I'm new to ruby and don't understand why the following code does what
> is does. Can anyone enlighten me?
>
> ruby -e 'a = [1,2,3,4,5,6,7,8,9,10]; a.each { |x| if (x === 2..5 )
> then print x, " " end}; puts '
> 2 3 4 5 6 7 8 9 10
>
> I would have thought this would be the same as
>
> ruby -e 'a = [1,2,3,4,5,6,7,8,9,10]; a.each { |x| case x; when 2..5
> then print x, " "; end}; puts '
> 2 3 4 5

Try switching x === 2..5 to 2..5 === x. The case equality operator
(===) is not cummutative. The conditions of a case statement are
evaluated using the when condition as the *receiver* of the case
equality operator, not the argument. Ie.

  case a
  when b
    ...
  end

is equivalent to:

  if b === a
    ...
  end

> I am also confused that
>
> ruby -e 'while gets; print  if /<div id=.*$/ .. /<\/body>/; end' < fred
> <div id="eutpuhe">
> UETHUEPUK
> THEUTEUH
> teuhepxn
> thueonhoe
> ononueuouh
> </div>
> </body>
>
> and a three . range test give the same output.
>
> ruby -e 'while gets; print  if /<div id=.*$/ ... /<\/body>/; end' < fred
> <div id="eutpuhe">
> UETHUEPUK
> THEUTEUH
> teuhepxn
> thueonhoe
> ononueuouh
> </div>
> </body>

Sorry, can't help you there. I always have a hard time remembering
what the difference between .. and ... are in that context. I stay
away from it in favor of more descriptive flagging in a while loop.
E.g.:

  flag = false
  while line = gets
    flag = true if line =~ /<div id=.*$/
    flag = false if line =~ /<\/body>/
    print line if flag
  end

Jacob Fugal