On 23-Oct-07, at 10:02 AM, Jes=FAs Gabriel y Gal=E1n wrote:

Hi,

> On 10/23/07, richard.j.dale / gmail.com <richard.j.dale / gmail.com> =20
> wrote:
>
>> Maybe 'enque' and 'deque' could be used as names for methods to put
>> items on the front of a Queue and remove items from the back =20
>> somewhere
>> in Ruby - then you wouldn't need push/pop and shift/unshift depending
>> on which end of the queue you were operating on.
>
> I like this:
>
> class Array
>    alias :enqueue :push
>    alias :dequeue :shift
> end
>
> Then you get Queue semantics and the start of the queue is the first
> element in the Array :-). (you could do enqueue --> unshift, dequeue
> --> pop if you rather have the first element of the queue the last in
> the array).
>

You have to be really careful here. Push/pop and shift/unshift are =20
not the same functions working on opposite ends of the array, no =20
matter what it sounds like from the documentation.

There is an issue with shift that I think amounts to a bug. Shift/=20
unshift work at the beginning of the array, so shift conceptually =20
requires moving array elements around. Ruby (and other programming =20
languages too, specifically some implementations of Common Lisp) =20
optimise shift so as to not have to actually move anything in memory. =20=

What it does is, more or less, to move the start of the array 'right' =20=

-- so no movement but there is now some part of the array before the =20
start of the array. The bug is that Ruby doesn't stomp on the cell of =20=

the array that is being shifted before the start, and so that cell =20
still contains a reference to some object (and IT IS INVISIBLE).

You say this will never happen? or rarely? Well, it's not 'never' for =20=

sure, and 'rarely' doesn't help much when you get caught by it. How =20
did I find out about it? Implementing a cache (the uncached stuff was =20=

hanging around in memory, intermittently since unshift will re-use =20
the parts of the array before the start). I also found (and reported, =20=

maybe even supplied a patch for) a problem in Mongrel's thread =20
management code that was using shift. How did I debug it the first =20
time? Don't ask.

I believe/hope that this will be fixed in some future version of Ruby.

This monkey patch fixes the problem, if this is how you want to solve =20=

it...

class Array
   alias :clingy_shift :shift

   def shift
     self[0] =3D nil
     clingy_shift
   end
end


Cheers,
Bob


> Jesus.
>

----
Bob Hutchison                  -- tumblelog at http://=20
www.recursive.ca/so/
Recursive Design Inc.          -- weblog at http://www.recursive.ca/=20
hutch
http://www.recursive.ca/       -- works on http://www.raconteur.info/=20
cms-for-static-content/home/