106
84

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 の配列で n 個ずつの要素を扱いたい

Posted at

each では要素を1つずつしか取得できないが、each_cons や each_slice を使用すればループ1回で複数個の要素を扱える。

each_cons(n) は連続した n 個の要素を1つずつずらしながら取得できる。

n = 3
[1, 2, 3, 4, 5].each_cons(n) do |a, b, c|
  puts "#{a}, #{b}, #{c}"
end
# >> 1, 2, 3
# >> 2, 3, 4
# >> 3, 4, 5

一方 each_slice(n) は n 個の要素を n ずつずらしながら取得する。

n = 3
[1, 2, 3, 4, 5, 6, 7, 8].each_slice(n) do |a, b, c|
  puts "#{a}, #{b}, #{c}"
end
# >> 1, 2, 3
# >> 4, 5, 6
# >> 7, 8,

使う機会は少ないかもしれないが、知らないと書くのが少し面倒だったりする(可読性的な意味で)。こういうメソッドがあるということくらいは知っておきたい。

106
84
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
106
84

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?