By some lingo "Java stlyle" iterators are called "external", "Ruby
style" ones are called "internal". I make this note just to separate
languages from concepts...
So, Ruby has built-in support for only for internal iterators, but ruby
also features callcc, which makes it easy to create external ones, too.
The generator package (part of the standard lib) implements this
concept.
While this approach is pretty elegant, the downside is a massive
performance loss.
Thus you might consider using a dumb solution, if there is one. Eg, a
typical case is when you want to iterate through two arrays
simultaneously -- then, unless you have huge arrays, it would be faster
to create a joint array by Array#zip or Array#transpose, and use its
each method, or just dup the arrays and shfit them.
Csaba
···
On Mon, Jun 20, 2005 at 07:52:30PM +0900, G?bor SEBESTY?N wrote:
Hi,
I need but actually don't find how to iterate an iterable collection
in Java-way. It seems generally like this:
Iterator it = objs.iterator();
while (it.hasMore()) {
Object anObj = it.next();
...
}
I want to get the first N pieces of "valid" objects from a collection. I would iterate in collection counting how many objects were sucessfully accepted and would break the cycle if there are no more objects or I already have my N objects. Here's my solution (written for Rails and the collection consists of ActiveRecord objects):
cl.each_with_index { |e,i|
i < n or break
c = _openChat(e.customer_id, @session[:user].id) and chats << c
}
Csaba
···
On Mon, Jun 20, 2005 at 11:31:09PM +0900, G?bor SEBESTY?N wrote:
On 2005.06.20., at 14:10, Robert Klemme wrote:
>What exactly do you want to do with the collection?
>
I want to get the first N pieces of "valid" objects from a
collection. I would iterate in collection counting how many objects
were sucessfully accepted and would break the cycle if there are no
more objects or I already have my N objects. Here's my solution
(written for Rails and the collection consists of ActiveRecord objects):
What exactly do you want to do with the collection?
I want to get the first N pieces of "valid" objects from a
collection. I would iterate in collection counting how many objects
were sucessfully accepted and would break the cycle if there are no
more objects or I already have my N objects. Here's my solution
(written for Rails and the collection consists of ActiveRecord
objects):