Melanie Fielder
10/8/2003 7:10:00 AM
Zoran Lazarevic <zoranlazarevic@yahoo.com> skrev i en
nyhedsmeddelelse:32c0bb6a.0310071950.55c75dd0@posting.google.com...
> Simon Strandgaard wrote in message news:...
> > On Mon, 06 Oct 2003 17:17:55 -0700, Zoran Lazarevic wrote:
> > > Can I iterate over multiple arrays/collections?
> > > Are there Iterators for enumerables, like in Java?
> >
> > Yes I have made some iterator classes.. But its not yet released.
> >
>
> Simon, the iterator class uses indexing ( @data[@position] ) and that
> is exactly what I tried to avoid. This does NOT work for collections
> that do not support indexing operator[] (e.g. linked lists, iterating
> through SQL resultset, etc.)
You can write an implicit iterator, like this:
server> cat snippet_implicit.rb
require 'iterator'
class ImplicitIterator < Iterator::Base
def initialize
super()
first
end
def first; @value = 0 end
def next; @value += 1 end
def is_done?; @value >= 10 end
def current; @value end
end
i = ImplicitIterator.new
until i.is_done?
p i.current
i.next
end
server> ruby snippet_implicit.rb
0
1
2
3
4
5
6
7
8
9
server>
Is this better ? :-)
> Apparently it is not possible to iterate using Collection.each over
> multiple collections. It is possible by using one thread per
> collection, but I do not want to go there.
You can make an iterator which can iterate over multiple iterators at
the same time, like this:
require 'iterator'
class MultiIterator < Iterator::Base
def initialize(*iterators)
@iterators = iterators
first
end
def first; @iterators.each{|i| i.first} end
def next; @iterators.each{|i| i.next} end
def is_done?
@iterators.each{|i| return true if i.is_done? }
false
end
def current; @iterators end
end
a = %w(a b c d e).create_iterator
b = (0..4).to_a.create_iterator
i = MultiIterator.new(a, b)
until i.is_done?
ia, ib = i.current
p [ia.current, ib.current]
i.next
end
Is this better ? ... I hope ;-)
--
Simon Strandgaard