"Simon Strandgaard" <neoneye / adslhome.dk> schrieb im Newsbeitrag
news:20040520123256.46e2f1c3.neoneye / adslhome.dk...
> Brian Schroeder <spam0504 / bssoftware.de> wrote:
> > for some time I'm wondering if there exists a library with
datastructures
> > like deque, queue, list, btree, and similar in ruby, such that I don't
> > have to implement them myself?
>
> deque, queue, list.. then ruby's builtin Array class will fit.
>
>
> server> irb
> irb(main):001:0> stack = []
> => []
> irb(main):002:0> stack.push(3)
> => [3]
> irb(main):003:0> stack.push(9)
> => [3, 9]
> irb(main):004:0> stack.push(10)
> => [3, 9, 10]
> irb(main):005:0> stack.pop
> => 10
> irb(main):006:0> stack.pop
> => 9
> irb(main):007:0> stack
> => [3]
> irb(main):008:0>

As queue:

irb(main):010:0> queue = []
=> []
irb(main):011:0> queue.push 1
=> [1]
irb(main):012:0> queue.push 2
=> [1, 2]
irb(main):013:0> queue.push 3
=> [1, 2, 3]
irb(main):014:0> queue.unshift
=> [1, 2, 3]
irb(main):015:0> queue.shift
=> 1
irb(main):016:0> queue.shift
=> 2
irb(main):017:0> queue.shift
=> 3
irb(main):018:0>

You can easily make that a bit more intuitive, if you like:

irb(main):018:0> class Array; alias :enq :push; alias :deq :shift; end
=> nil
irb(main):019:0> queue = []
=> []
irb(main):020:0> queue.enq 1
=> [1]
irb(main):021:0> queue.enq 2
=> [1, 2]
irb(main):022:0> queue.enq 3
=> [1, 2, 3]
irb(main):023:0> queue.deq
=> 1
irb(main):024:0> queue.deq
=> 2
irb(main):025:0> queue.deq
=> 3
irb(main):026:0> queue.deq
=> nil


And there's also a thread safe queue:

$ irb -r thread
irb(main):001:0> queue = Queue.new
=> #<Queue:0x1017ad68 @que=[], @waiting=[]>
irb(main):002:0> queue.enq 1
=> nil
irb(main):003:0> queue.enq 2
=> nil
irb(main):004:0> queue.enq 3
=> nil
irb(main):005:0> queue
=> #<Queue:0x1017ad68 @que=[1, 2, 3], @waiting=[]>
irb(main):006:0> queue.deq
=> 1
irb(main):007:0> queue.deq
=> 2
irb(main):008:0> queue.deq
=> 3

Regards

    robert