1

Well, I haven't found a clean solution to write this code easily in Ruby:

# Java style version:
array.each do |i, el|
  if i < array.length - 1
     process(array[i], array[i+1])
  end
end

# Would be nice if I could do something like this:
array.each do |i, el, next|
  process(el, next)
end
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206

2 Answers2

8

You can use each_cons:

array.each_cons(2) do |a, b|
  process(a, b)
end
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
2
ar = [1,2,3,4]
(ar.size - 1).times {|i| process ar[i],ar[i+1]}
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317