From: Justin Collins Date: 2009-10-03T03:35:21+09:00 Subject: Re: Rolling String Buffer needed Matt Brooks wrote: > Aaron Patterson wrote: > >> class MyBuff >> def initialize max_size, filename >> @max_size = max_size >> @list = [] >> @file = File.open(filename, 'wb') >> end >> >> def push string >> @list.push string >> while @list.length > @max_size >> @file.write @list.pop >> end >> end >> >> def [] i >> @list[i] >> end >> end >> >> --- >> Aaron Patterson >> http://tenderlovemaking.com >> > > > That looks great! So when I do pop on an array it does the highest > index element? And when you push onto an array it puts it in index 0 ? > > Thanks! > Matt > > Actually, push/pop works like it's a stack, with the top being the last element. So pop removes and returns the last element, while push appends to the end. irb(main):001:0> a = [1,2,3,4] => [1, 2, 3, 4] irb(main):002:0> a.pop => 4 irb(main):003:0> a.push 5 => [1, 2, 3, 5] irb(main):004:0> a.pop => 5 irb(main):005:0> a => [1, 2, 3] If you want it to act like a queue with the first element being the head, then use shift/push. rb(main):001:0> a = [1,2,3,4] => [1, 2, 3, 4] irb(main):002:0> a.shift => 1 irb(main):003:0> a.push 5 => [2, 3, 4, 5] irb(main):004:0> a.shift => 2 irb(main):005:0> a => [3, 4, 5] If you want it to act like a queue with the last element being the head, then use pop/unshift. irb(main):001:0> a = [1,2,3,4] => [1, 2, 3, 4] irb(main):002:0> a.pop => 4 irb(main):003:0> a.unshift 5 => [5, 1, 2, 3] irb(main):004:0> a.pop => 3 irb(main):005:0> a => [5, 1, 2] -Justin