What should this print?

Hi Bouquet,

Hi,

I was expecting the code below to print 1, 1,
but I get 1, nil.

old = nil
[1,1].each do |n|
   if n != old
     x = 1
     old = n
   end
   p x
end

Thanks.

1. old = nil
2. [1,1].each do |n|
3. if n != old
4. x = 1
5. old = n
6. end
7. p x
8. end

old was declared *outside* the each block at (1), so its remembered in,
as well as after the each block.

old = nil
[1,1].each do |n|
   if n != old
     x = 1
     old = n
   end
   p x
end
puts "old outside the block: #{old}"

x declared *inside* the each block at (4), *only* when the if condition
is true! The first iteration (the first 1 in [1,1] at (2)), n doesn't
equal old (n=1, old=nil) so the if condition is true. So x is initiated
to 1, old becomes 1.
   p x #=> prints 1
Now, (and this is a newbies understanding), at the end of this first
iteration at (8) x is forgotten. ie not available during the second
iteration.

If we start the second iteration, n=1 (the second 1 in [1,1] at (2)
and old (which *is* still available because it was declared outside the
each block) = 1. So if n=1 and old=1, we would never enter the if
statement at (3) and x would not be initiated. Hence p as nil.

Try this:

    old = nil
    [1,1].each do |n|
       if n != old
         x = 1
         old = n
       else
         x = "what am I?"
       end
       p x
    end

and this:

    old = nil
    x = nil
    [1,1].each do |n|
       if n != old
         x = 1
         old = n
       end
       p x
    end

cheers,

···

On Sun, 02 Mar 2008 05:04:47 GMT Bouquet <news@soma.bpa.nu> wrote:

--
Mark