Is there an algorithm to extract values in duets from an array and operate over them? [duplicate]
I have an array like:
[1,2,3,4,5,6,7,8,9]
And I want to get items in duets like this:
- 1,2
- Do some operations...
- 2,3
- Do some operations...
- 3,4
- Do some operations...
- 4,5
- Do some operations...
- 5,6
- Do some operations...
- 6,7
- Do some operat开发者_Go百科ions...
- 7,8
- Do some operations...
- 8,9
- Do some operations...
Please suggest an elegant way to achieve this using Ruby.
[1,2,3,4,5,6,7,8,9].each_cons 2 do |a,b|
p [a,b]
end
You want Enumerable#each_cons:
[1,2,3,4,5,6,7,8,9].each_cons(2){|pair| p pair}
精彩评论