3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyで配列を一つずらした組み合わせが欲しい時のイディオム

Posted at

Arrayクラスのeach_consメソッドを使う

[1,2,3,4,5].each_cons(2).to_a #=> [[1, 2], [2, 3], [3, 4], [4, 5]]
[1,2,3,4,5].each_cons(2).map { |x, y| x + y } #=> [3, 5, 7, 9]

3つづつ欲しければeach_consに3を渡せばいい

[1,2,3,4,5].each_cons(3).to_a # => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?