开发者

Is there an algorithm to extract values in duets from an array and operate over them? [duplicate]

This question already has answers here: Ruby array access 2 consecutive(chained) elements at a time (4 answers) Closed 4 years ago.

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
  • 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}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜