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?
On Dec 14, 2007 4:28 PM, Jari Williamsson <jari.williamsson@mailbox.swipnet.se> 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?
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.
Best regards,
Jari Williamsson
--Greg
···
On Sat, Dec 15, 2007 at 12:28:51AM +0900, Jari Williamsson wrote:
On Dec 14, 2007, at 10:28 AM, 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?
On Dec 14, 8:28 am, Jari Williamsson <jari.williams...@mailbox.swipnet.se> 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?
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.