Array#each_cons(cnt) について

Rubyのメソッドeach_consについて

  • Array#each_cons(cnt)はselfからcnt個ずつ要素を取り出す
  • ブロックに渡す。
  • ブロック引数には配列で渡される。
  • 取り出す要素は、[要素1, 要素2, 要素3], [要素2, 要素3, 要素4] ...と1つづ前に進みます。
  • 似たメソッドにArray#each_slice(cnt)がある。
arr = (1..30).to_a
container = []

arr.each_cons(7) do |i|
  container << i
end

p container

# [[1, 2, 3, 4, 5, 6, 7], 
# [2, 3, 4, 5, 6, 7, 8], 
# [3, 4, 5, 6, 7, 8, 9], 
# [4, 5, 6, 7, 8, 9, 10], 
# [5, 6, 7, 8, 9, 10, 11], 
# [6, 7, 8, 9, 10, 11, 12], 
# [7, 8, 9, 10, 11, 12, 13], 
# [8, 9, 10, 11, 12, 13, 14], 
# [9, 10, 11, 12, 13, 14, 15], 
# [10, 11, 12, 13, 14, 15, 16], 
# [11, 12, 13, 14, 15, 16, 17], 
# [12, 13, 14, 15, 16, 17, 18], 
# [13, 14, 15, 16, 17, 18, 19], 
# [14, 15, 16, 17, 18, 19, 20], 
# [15, 16, 17, 18, 19, 20, 21], 
# [16, 17, 18, 19, 20, 21, 22], 
# [17, 18, 19, 20, 21, 22, 23], 
# [18, 19, 20, 21, 22, 23, 24], 
# [19, 20, 21, 22, 23, 24, 25], 
# [20, 21, 22, 23, 24, 25, 26], 
# [21, 22, 23, 24, 25, 26, 27], 
# [22, 23, 24, 25, 26, 27, 28], 
# [23, 24, 25, 26, 27, 28, 29], 
# [24, 25, 26, 27, 28, 29, 30]]
arr = (1..30).to_a
container = []

arr.each_cons(7) do |i|
  container << i
end

p container.length

#24
(1..10).each_slice(3) {|arr| p arr }

# <実行結果>
# [1, 2, 3]
# [4, 5, 6]
# [7, 8, 9]
# [10]