From: Drew Olson Date: 2007-08-09T04:05:26+09:00 Subject: Re: Iterating list in pairs FireAphis wrote: > Hello, > > I need to iterate through a list and handle two elements on every > iteration. That is I'd like to do something like Weird, I just blogged about this topic: http://drewolson.wordpress.com/. I did it using the zip method, something like this (I added block handling to this example): class Array def adjacent_pairs if block_given? self[0..-2].zip(self[1..-1]).each do |a,b| yield a,b end else self[0..-2].zip(self[1..-1]) end end end Now we can do either of the following: irb(main):012:0> [1,2,3,4].adjacent_pairs => [[1, 2], [2, 3], [3, 4]] irb(main):013:0> [1,2,3,4].adjacent_pairs do |a,b| irb(main):014:1* puts "#{a} #{b}" irb(main):015:1> end 1 2 2 3 3 4 => [[1, 2], [2, 3], [3, 4]] -- Posted via http://www.ruby-forum.com/.