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?
On Sat, Dec 15, 2007 at 12:28:51AM +0900, Jari W. 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:
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?
Take your pick:
irb(main):001:0> a = %w| a b c d e f g h |
=> [“a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”]
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?
Best regards,
Jari W.
require ‘enumerator’
[first, second, third].each_slice(2) do |prev,curr|
do stuff
end
Except that you don’t get a [nil,first] pair to start, you get
[first,second].
You could also do something like:
[first, second, third].inject(nil) do |prev, curr|
do stuff
curr
end
And curr is assigned to prev in the next iteration and the first
iteration gets [nil,first]