From: dblack@... Date: 2007-08-08T22:49:46+09:00 Subject: Re: Iterating list in pairs Hi -- On Wed, 8 Aug 2007, Jano Svitok wrote: > On 8/8/07, 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 >> >> [1,2,3,4,5].each { |x, y| puts x.to_s + y.to_s } >> >> 12 >> 23 >> 34 >> 45 >> >> This code doesn't work off course. >> I can iterate using indices >> >> 0.upto(list.size-1) { |i| puts list[i] + list[i+1] } >> >> But it looks ugly to me. Do you know any elegant tricks that don't use >> list indices? >> >> Thanks >> FireAphis > > Enumerable#each_slice(n) {|...| ...} That won't work because it won't double back; you'll get 12, 34, 5 instead of 12, 23, 34, 45. However, you reminded me of something: require 'enumerator' [1,2,3,4,5].enum_cons(2).each {|a,b| puts "#{a}#{b}" } David -- * Books: RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242) RUBY FOR RAILS (http://www.manning.com/black) * Ruby/Rails training & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)