[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

going over two interators

mgarriss

9/17/2003 11:24:00 PM

I often find that I need to go over two enumerables in parallel. I have
used a little method called 'both' for this:

irb
arr1 = [1,2,3,4,5]
--> [1, 2, 3, 4, 5]
arr2 = [6,7,8,9,10]
--> [6, 7, 8, 9, 10]
def both( enum1, enum2 )
enumC = enum2.dup
enum1.each do |e1|
yield e1, enumC.shift
end
end
--> nil
both( arr1, arr2 ) do |a,b|
puts "#{a} : #{b}"
end
1 : 6
2 : 7
3 : 8
4 : 9
5 : 10
--> [1, 2, 3, 4, 5]


It assumes that enum1 is at least at big as enum2.

Is there a way someone can think of that's more efficient then this?
Namely getting rid of the 'dup'. Or maybe I'm missing some rubyism that
would make this easier.

TIA,
Michael


2 Answers

mgarriss

9/17/2003 11:27:00 PM

0

Michael Garriss wrote:

> I often find that I need to go over two enumerables in parallel. I
> have used a little method called ''both'' for this:
>
> irb
> arr1 = [1,2,3,4,5]
> --> [1, 2, 3, 4, 5]
> arr2 = [6,7,8,9,10]
> --> [6, 7, 8, 9, 10]
> def both( enum1, enum2 )
> enumC = enum2.dup
> enum1.each do |e1|
> yield e1, enumC.shift
> end
> end
> --> nil
> both( arr1, arr2 ) do |a,b|
> puts "#{a} : #{b}"
> end
> 1 : 6
> 2 : 7
> 3 : 8
> 4 : 9
> 5 : 10
> --> [1, 2, 3, 4, 5]
>
>
> It assumes that enum1 is at least at big as enum2.
>
> Is there a way someone can think of that''s more efficient then this?
> Namely getting rid of the ''dup''. Or maybe I''m missing some rubyism
> that would make this easier.
>

I just realized that a) my spell checker doesn''t look at the subject
line, and that b) this only works for arrays. How could I make it work
(well) for any enumerable?

Michael