On 14.12.2007 16:39, Gregory Seidman wrote: > On Sat, Dec 15, 2007 at 12:28:51AM +0900, Jari Williamsson wrote: >> I'm going through lots of data where the result of the current is affected >> by the previous element. So what I would need is an >> "each_with_previous {|current, prev|}" >> ...to make it a bit more readable. Is there any built-in Ruby method that I >> might have overlooked, or should I build my own? > > You can fake it pretty simply with inject. For example: > >>> [ 1,2,3,4,5 ].inject { |prev,cur| puts "#{prev}, #{cur}"; cur } > 1, 2 > 2, 3 > 3, 4 > 4, 5 > > Note that you do need the block to "return" (i.e. evaluate to) the current > element so that it gets passed into the next iteration. There is a subtlety: with your code there will be no previous for the first element. Depending on what the OP needs you can as well do irb(main):001:0> (1..5).inject(nil) {|prev,curr| p [prev,curr];curr} [nil, 1] [1, 2] [2, 3] [3, 4] [4, 5] => 5 Jari, what kind of calculation do you do? Cheers robert