Csaba Henk wrote:
> 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):
>>
>>         cl = CustomerQueue.find(:all, :conditions => cond, :order =>
>> "created_at ASC")
>>
>>         i = 0
>>         while i < cl.size and n > 0
>>             c = _openChat(cl[i].customer_id, @session[:user].id)
>>             unless c.nil?
>>                 chats << c
>>                 n = n - 1
>>             end
>>         end
>>
>> I don't like referencing by index. That's why I asked you how to
>> implement this using iterator and not a simple while cycle with
>> indexing.
>
> Maybe
>
>  cl.each_with_index { |e,i|
>    i < n or break
>    c = _openChat(e.customer_id, @session[:user].id) and chats << c
>  }

Nah, this cries for #inject!

found = collection.inject([]) do |f,x|
  if check_condition(x)
    f << x
    break f if f.size >= 10
  end
  f
end

>> (0..100).inject([]){|f,x| if x%3==0 then f << x; break f if f.size ==
10 end; f}
=> [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
>> (0..10).inject([]){|f,x| if x%3==0 then f << x; break f if f.size == 10
end; f}
=> [0, 3, 6, 9]

:-)

Kind regards

    robert