Alex Young
8/8/2007 1:44:00 PM
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?
irb(main):001:0> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):002:0> a[0,4].zip(a[1,5]).each{|x,y| puts x.to_s + y.to_s}
12
23
34
45
=> [[1, 2], [2, 3], [3, 4], [4, 5]]
Unless a[0,4] breaks your "no list indices" rule, of course :-)
--
Alex