31

现在,这是数组,

[1,2,3,4,5,6,7,8,9]

我想,

[1,2],[2,3],[3,4] upto [8,9]

当我这样做时, each_slice(2) 我得到,

[[1,2],[3,4]..[8,9]]

我目前正在这样做,

arr.each_with_index do |i,j|
  p [i,arr[j+1]].compact #During your arr.size is a odd number, remove nil.
end

有没有更好的办法??

4

4 回答 4

58

Ruby 读懂了你的想法。你想要连续的元素吗?

[1, 2, 3, 4, 5, 6, 7, 8, 9].each_cons(2).to_a
# => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]
于 2013-03-28T12:50:41.107 回答
7

.each_cons做你想要的。

[1] pry(main)> a = [1,2,3,4,5,6,7,8,9]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
[2] pry(main)> a.each_cons(2).to_a
=> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]
于 2013-03-28T12:49:17.940 回答
6

你几乎是对的:)

arr = [1,2,3,4,5,6,7,8,9]
arr.each_cons(2) do |chunk|
  p chunk
end
# >> [1, 2]
# >> [2, 3]
# >> [3, 4]
# >> [4, 5]
# >> [5, 6]
# >> [6, 7]
# >> [7, 8]
# >> [8, 9]
于 2013-03-28T12:49:48.377 回答
1

如果您想实现自己的each_cons

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
cons = 2

0.upto(arr.size - cons) do |i|
  p arr[i, cons]
end

输出:

[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
于 2018-02-16T12:09:21.993 回答